Laravel Eloquent ->whereHas() uses anexists() subquery - https://dev.mysql.com/doc/refman/8.0/en/exists-and-not-exists-subqueries.html - in order to return your results.
I would like to write my own subquery, but I do not know how to tell Eloquent to ->where it.
If I do:
$query->where( DB::raw(' exists( subquery ) ')
Laravel instead writes the subquery as:
where exists( subquery ) is null
So I'm just wondering what $query->method() could be used to add an exists() subquery to the 'where' statements. The subquery would be just the same kind that laravel generates, but written out:
... and exists ( select * from `tbl` inner join `assets` on `custom_assets`.`id` = `tbl`.`asset_id` where `assets`.`deleted_at` is null and `users`.`id` = `assets`.`client_id` and `field_id` = ? and (`value` = ? and `assets`.`deleted_at` is null )
Use whereRaw():
$query->whereRaw('exists( subquery )')
Read WhereHas Description Here
You can find this code example there. You can also add a closure for you custom query in whereHas.
// Retrieve all posts with at least one comment containing words like foo%
$posts = App\Post::whereHas('comments', function ($query) {
$query->where('content', 'like', 'foo%');
})->get();
Related
How to order laravel eloquent query using parent model?
I mean I have an eloquent query where I want to order the query by its parent without using join relationship?
I used whereHas and order by on it, but did not work.
Here is a sample of my code:
$query = Post::whereHas('users')->orderBy('users.created_at')->get();
If you want to order Post by a column in user you have to do a join in some way unless you sort after you retrieve the result so either:
$query = Post::select('posts.*')
->join('users', 'users.id', 'posts.user_id')
->orderBy('users.created_at')->get();
Note that whereHas is not needed anymore because the join (which is an inner join by default) will only result in posts that have a user.
Alternatively you can do:
$query = Post::has('users')
->with('users')
->get()
->sortBy(function ($post) { return $post->users->created_at; });
The reason is that eloquent relationships are queried in a separate query from the one that gets the parent model so you can't use relationship columns during that query.
I have no clue why you wanted to order Posts based on their User's created_at field. Perhaps, a different angle to the problem is needed - like accessing the Post from User instead.
That being said, an orderBy() can accept a closure as parameter which will create a subquery then, you can pair it with whereRaw() to somewhat circumvent Eloquent and QueryBuilder limitation*.
Post::orderBy(function($q) {
return $q->from('users')
->whereRaw('`users`.id = `posts`.id')
->select('created_at');
})
->get();
It should generate the following query:
select *
from `posts`
order by (
select `created_at`
from `users`
where `users`.id = `posts`.id
) asc
A join might serve you better, but there are many ways to build queries.
*As far as I know, the subquery can't be made to be aware of the parent query fields
You can simply orderBy in your Post model.
public function users(){
return $this->belongsTo(User::class, "user_id")->orderByDesc('created_at');
}
I hope this helps you.
You can try
Post::query()
->has('users')
->orderBy(
User::select('created_at')
->whereColumn('id', 'posts.user_id')
->orderBy('created_at')
)
->get();
The sql generated would be like
select * from `posts`
where exists (select * from `users` where `posts`.`user_id` = `users`.`id`)
order by (select `created_at` from `users` where `id` = `posts`.`user_id` order by `created_at` asc) asc
But I guess join would be a simpler approach for this use case.
Laravel Docs - Eloquent - Subquery Ordering
i have this query to return data from two tables based on DISTINCT destination_tbls.destination
like the following:
SELECT DISTINCT
destination_tbls.destination,
MIN(sms_details.id),
MIN(sms_details.msg_timestamp) AS TIMESTAMP,
MIN(destination_tbls.count)
FROM
sms_details
JOIN
(
SELECT
*
FROM
destination_tbls
)
destination_tbls
ON destination_tbls.id = sms_details.destination_tbls_id
GROUP BY
destination_tbls.destination;
Now how to use the paginate with them,
I tried something like this but don't work:
DB::select('
SELECT DISTINCT destination_tbls.destination,MIN(sms_details.id),MIN(sms_details.msg_timestamp) AS TIMESTAMP,MIN(destination_tbls.count)
FROM sms_details
JOIN(SELECT * FROM destination_tbls) destination_tbls ON destination_tbls.id=sms_details.destination_tbls_id
GROUP BY destination_tbls.destination
')->simplePaginate(100);
Any help would be appreciated!
If you want to use laravel's pagination, you need to write the query using the query builder methods.
$results = DB::table('sms_details')
->select('destination_tbls.destination')
->selectRaw('min(sms_details.id)')
->selectRaw('min(sms_details.msg_timestamp) as timestamp')
->selectRaw('min(destination_tbls.count)')
->distinct()
->joinSub(
function ($sub) {
$sub->from('destination_tbls');
},
'destination_tbls',
function ($join) {
$join->on('destination_tbls.id', '=', 'sms_details.destination_tbls_id');
}
)
->groupBy('destination_tbls.destination')
->simplePaginate(100);
Since you're not really doing anything in the subquery join, you could join the table instead.
$query = DB::table('sms_details')
->select('destination_tbls.destination')
->selectRaw('min(sms_details.id)')
->selectRaw('min(sms_details.msg_timestamp) as timestamp')
->selectRaw('min(destination_tbls.count)')
->distinct()
->join('destination_tbls', 'destination_tbls.id', '=', 'sms_details.destination_tbls_id')
->groupBy('destination_tbls.destination')
->simplePaginate(100);
Good morning,
I've been trying for quite a lot of time to translate this query(which returns an array of stdClass) into query builder so I could get objects back as Eloquent models.
This is how the query looks like untranslated:
$anketa = DB::select( DB::raw("SELECT *
FROM v_anketa a
WHERE not exists (select 1 from user_poeni where anketa_id=a.id and user_id = :lv_id_user)
Order by redni_broj limit 1"
), array( 'lv_id_user' => $id_user,
));
I have tried this, but it gives a syntax error near the inner from in the subquery:
$anketa = V_anketa::selectRaw("WHERE not exists (select 1 from user_poeni where anketa_id=a.id and user_id = :lv_id_user)", array('lv_id_user' => $id_user,)
)->orderBy('redni_broj')->take(1)->first();
The problem is this exists and a subquery in it. I couldn't find anything regarding this special case.
Assume each table has an appropriate Eloquent model.
V_anketa is a view. The db is postgresql.
As far as the query goes I believe this should work:
$anketa = V_anketa::whereNotExists(function ($query) use ($id_user) {
$query->select(DB::raw(1))
->from('user_poeni')
->where('anketa.id', '=', 'a.id')
->where('user_id', '=', $id_user);
})
->orderBy('redni_broj')
->first();
but I'm not clear on what do you mean by "assuming every table has an Eloquent model" and "V_anketa" is a view...
Assuming the SQL query is correct, this should work:
$anketa = DB::select(sprintf('SELECT * FROM v_anketa a WHERE NOT EXISTS (SELECT 1 FROM user_poeni WHERE anketa_id = a.id AND user_id = %s) ORDER BY redni_broj LIMIT 1', $id_user));
If you want to get back an Builder instance you need to specify the table:
$anketa = DB::table('')->select('');
If you however, want to get an Eloquent Model instance, for example to use relations, you need to use Eloquent.
I have a sql query:
select `id` from `users`
where (
select count(*)
from `user_event` as `uev`
where `uev`.`leader_id` = `users`.`id`
) > 1
How can I convert it to Eloquent Laravel?
Assuming you have set up the relationship you can use the has() method for that:
$users = User::select('id')->has('events', '>', 1)->get();
If you want an array of users ids (since you're only selecting the id) you can also use lists():
$ids = User::has('events', '>', 1)->lists('id');
Since you asked, this would be an alternative method (not tested though)
User::where(DB::raw('1'), '<', function($q){
$q->from('user_event')
->where('user_event.leader_id', 'users.id');
})->get();
I'm getting some unexpected results when running an Eloquent join query. I get two different results from using the exact same query. One running with DB::raw(), the second with Eloquent.
In the Eloquent query, the Users that matches the
where squad_user.leave_time >= seasons.start_time
are missing and will not be included in the result set. The users that matches the
or squad_user.leave is null
will be included, however.
That's the only difference in the results from the two queries. The raw query actually produces the desired result set.
What really puzzles me is, if I check the query logs, both Laravel's and MySQL, I get the exact same query when running both the raw and Eloquent query.
Raw query (the actual query i get from the query log when running the Eloquent query)
return \DB::select(\DB::raw('
select users.*
from users
inner join squad_user on users.id = squad_user.user_id
inner join seasons on squad_user.squad_id = seasons.squad_id
where squad_user.join_time <= seasons.end_time
and (squad_user.leave_time >= seasons.start_time or squad_user.leave_time is null)
and seasons.id = :seasonId
'),
['seasonId' => 3]
);
Eloquent query
return User::join('squad_user', 'users.id', '=', 'squad_user.user_id')
->join('seasons', 'squad_user.squad_id', '=', 'seasons.squad_id')
->where('squad_user.join_time', '<=', 'seasons.end_time')
->where(function ($query)
{
$query->where('squad_user.leave_time', '>=', 'seasons.start_time')
->orWhereNull('squad_user.leave_time');
})
->where('seasons.id', 3)
->get(['users.*']);
Laravel's Eloquent query log
select `users`.*
from `users`
inner join `squad_user` on `users`.`id` = `squad_user`.`user_id`
inner join `seasons` on `squad_user`.`squad_id` = `seasons`.`squad_id`
where `squad_user`.`join_time` <= seasons.end_time
and (`squad_user`.`leave_time` >= seasons.start_time or `squad_user`.`leave_time` is null)
and `seasons`.`id` = 3
{"bindings":["seasons.end_time","seasons.start_time",3],"time":0.38,"name":"mysql"}
MySQL's general_log on the Eloquent query
select `users`.*
from `users`
inner join `squad_user` on `users`.`id` = `squad_user`.`user_id`
inner join `seasons` on `squad_user`.`squad_id` = `seasons`.`squad_id`
where `squad_user`.`join_time` <= ?
and (`squad_user`.`leave_time` >= ? or `squad_user`.`leave_time` is null)
and `seasons`.`id` = ?
MySQL's general_log on the Raw query
select users.*
from users
inner join squad_user on users.id = squad_user.user_id
inner join seasons on squad_user.squad_id = seasons.squad_id
where squad_user.join_time <= seasons.end_time
and (squad_user.leave_time >= seasons.start_time or squad_user.leave_time is null)
and seasons.id = ?
I would appreciate any pointers here, as I am very lost.
where binds 3rd param and treats it usually as a string, unless you tell it not to by using raw statement. DB::raw or whereRaw will work for you:
return User::join('squad_user', 'users.id', '=', 'squad_user.user_id')
->join('seasons', 'squad_user.squad_id', '=', 'seasons.squad_id')
->where('squad_user.join_time', '<=', DB::raw('seasons.end_time'))
->where(function ($query)
{
$query->where('squad_user.leave_time', '>=', DB::raw('seasons.start_time'))
->orWhereNull('squad_user.leave_time');
})
->where('seasons.id', 3)
->get(['users.*']);
Since Laravel Verion 5.2 you can also use whereColumn to verify that two columns are equal (or pass a comparison operator to the method):
->whereColumn('squad_user.join_time', '<=', 'seasons.end_time')