Reputation: 4944
I remember the old days "discovering" it in a query using the Eloquent, if I used the with
Laravel do aninner join
.
Today by chance I checked the queries of a project and ...
[2014-11-20 23:21:16] sql.INFO: select * from `ocurrences` where `ocurrences`.`deleted_at` is null order by RAND() limit 4 {"bindings":[],"time":3.58,"name":"mysql"} []
[2014-11-20 23:21:16] sql.INFO: select * from `users` where `users`.`id` in ('7') {"bindings":["7"],"time":0.49,"name":"mysql"} []
[2014-11-20 23:21:16] sql.INFO: select * from `users` where `users`.`id` = '7' limit 1 {"bindings":["7"],"time":0.51,"name":"mysql"} []
[2014-11-20 23:21:16] sql.INFO: select * from `tags` limit 5 {"bindings":[],"time":0.41,"name":"mysql"} []
In this case, I'm doing a query like this:
/**
* Get random ocurrences for home
* @return mixed
*/
public static function randomForHome()
{
return static::with('user')
->orderByRaw('RAND()')
->limit(4)
->get();
}
What is wrong and/or how do I do joins with Eloquent?
Upvotes: 1
Views: 108
Reputation: 4944
I found the solution in a Laracasts video (thanks Jeffrey!).
I need to use join('users', 'users.id', '=', 'ocurrences.user_id')
. It's a bit logical but I thought with do joins too.
Anyway, here's the final solution:
/**
* Get random ocurrences for home
* @return Eloquent
*/
public static function randomForHome()
{
return static::join('users', 'users.id', '=', 'ocurrences.user_id')
->orderByRaw('RAND()')
->limit(4)
->get();
}
Thanks guys.
Upvotes: 1