请考虑以下内容:
$posts = $this->model->newQuery()
->whereIn('user_id', $user->following) // specifically this line
->orWhere('user_id', $user->id)
->get();
上述问题是有两个查询:
$user->following
使用子查询会更有效,但是,我实际上不记得正确的方法了...
我尝试了以下所有操作:
// This was a long-shot...
...->whereIn('user_id', function ($query) use ($user) {
$query->raw($user->following()->toSql());
});
// This works but pretty sure it can be done better with eloquent...
...->whereIn('user_id', function ($query) use ($user) {
$query->select('follow_id')
->from('user_follows')
->where('user_id', $user->id);
});
有没有一种方法可以通过使用先前定义的关系$user->following()
来实现,而不是像上面的最后一个示例那样手动定义关系查询?
following
关系定义如下:
/**
* Get the users that the user follows.
*/
public function following()
{
return $this->belongsToMany('SomeApp\User\Models\User', 'user_follows', 'user_id', 'follow_id')
->withTimestamps();
}
答案 0 :(得分:3)
使用此:
->whereIn('user_id', $user->following()->getQuery()->select('id'))