雄辩的渴望加载不加入?

时间:2014-11-20 23:40:33

标签: php laravel laravel-4 eloquent

我记得过去的日子"发现"它在使用Eloquent的查询中,如果我使用with Laravel执行inner join

今天我偶然检查了一个项目的查询......

[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"} []

在这种情况下,我正在进行这样的查询:

/**
 * Get random ocurrences for home
 * @return mixed
 */
public static function randomForHome()
{
  return static::with('user')
    ->orderByRaw('RAND()')
    ->limit(4)
    ->get();
}

有什么问题和/或我如何加入Eloquent

1 个答案:

答案 0 :(得分:1)

我在Laracasts视频中找到了解决方案(感谢Jeffrey!)。

我需要使用join('users', 'users.id', '=', 'ocurrences.user_id')。这有点合乎逻辑,但我认为也加入了。

无论如何,这是最终的解决方案:

/**
 * 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();
}

谢谢你们。