在 Eloquent 中模拟右连接
Simulating a right join in Eloquent
我有一个模型 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);
}
我有一个模型 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);
}