我有一个 Person
模型,它 belongsToMany
Review
对象。
这一切都运行良好,我可以成功查询。
我现在想做的是查询所有没有与之关联的 Review
的 Person
。
我尝试过类似的事情
Person::with('reviews')->whereNull('reviews.id')->get();
和
Person::whereHas('reviews', function($q)
{
$q->whereNull('id');
})->get();
但没有成功 - 我需要做什么才能获取没有 Review
对象的 Person
对象?
这对于普通 SQL 来说非常容易,但我有很多其他代码使用 Eloquent 模型,所以我想在这里继续使用 Eloquent。
最佳答案
尝试whereDoesntHave
:
Person::whereDoesntHave('reviews')->get();
Add a relationship count condition to the query.
来自Illuminate/database/Eloquent/Builder.php的方法(参见代码here):
public function whereDoesntHave($relation, Closure $callback = null)
{
return $this->doesntHave($relation, 'and', $callback);
}
调用:
/**
* Add a relationship count condition to the query.
*
* @param string $relation
* @param string $boolean
* @param \Closure|null $callback
* @return \Illuminate\Database\Eloquent\Builder|static
*/
public function doesntHave($relation, $boolean = 'and', Closure $callback = null)
{
return $this->has($relation, '<', 1, $boolean, $callback);
}
关于php - 在 Eloquent 中模拟右连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29875913/