Using Model Relationship in a Single Query

Consider the following:

$posts = $this->model->newQuery()
    ->whereIn('user_id', $user->following) // specifically this line
    ->orWhere('user_id', $user->id)
    ->get();

The problem with the above is that there are two queries:

  • Get following: $user->following
  • Get posts: Above

This would be much more efficient with the use of a subquery, however, I cannot actually remember the correct way to do it...

I have tried all of the 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);
});

Is there a way that this can be achieved by using the previously defined relationship $user->following() instead of manually defining the relationship query like the last example above?

Reference

The following relationship is defined as follows:

/**

  • Get the users that the user follows.
    */
    public function following()
    {
    return $this->belongsToMany(‘SomeApp\User\Models\User’, ‘user_follows’, ‘user_id’, ‘follow_id’)
    ->withTimestamps();
    }


#php #laravel

3 Likes1.50 GEEK