在单个查询中使用模型关系

时间:2019-01-30 00:43:57

标签: php laravel eloquent

请考虑以下内容:

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

1 个答案:

答案 0 :(得分:3)

使用此:

->whereIn('user_id', $user->following()->getQuery()->select('id'))