Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/246.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在单个查询中使用模型关系_Php_Laravel_Eloquent - Fatal编程技术网

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

Php 在单个查询中使用模型关系,php,laravel,eloquent,Php,Laravel,Eloquent,考虑以下几点: $posts = $this->model->newQuery() ->whereIn('user_id', $user->following) // specifically this line ->orWhere('user_id', $user->id) ->get(); // This was a long-shot... ...->whereIn('user_id', function ($que

考虑以下几点:

$posts = $this->model->newQuery()
    ->whereIn('user_id', $user->following) // specifically this line
    ->orWhere('user_id', $user->id)
    ->get();
// 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
  • 获取帖子:以上
使用子查询会更有效,但是,我实际上记不起正确的方法

我尝试了以下所有方法:

$posts = $this->model->newQuery()
    ->whereIn('user_id', $user->following) // specifically this line
    ->orWhere('user_id', $user->id)
    ->get();
// 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()
而不是像上面的最后一个示例那样手动定义关系查询来实现这一点

参考文献 以下关系定义如下:

/**
 * Get the users that the user follows.
 */
public function following()
{
    return $this->belongsToMany('SomeApp\User\Models\User', 'user_follows', 'user_id', 'follow_id')
        ->withTimestamps();
}
使用以下命令:

->whereIn('user_id', $user->following()->getQuery()->select('id'))
使用以下命令:

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

请添加
以下的
关系。@JonasStaudenmeir请参阅修正案:-请添加
以下的
关系。@JonasStaudenmeir请参阅修正案:-DFantastic,这正是我要找的那种东西!现在无法进行测试,因为我的电脑已不再使用,但明天将进行测试并接受第一件事。非常感谢。太棒了,这正是我要找的东西!现在无法进行测试,因为我的电脑已不再使用,但明天将进行测试并接受第一件事。非常感谢。