php - 在 Eloquent 中模拟右连接

标签 php laravel eloquent

我有一个 Person 模型,它 belongsToMany Review 对象。

这一切都运行良好,我可以成功查询。

我现在想做的是查询所有没有与之关联的 ReviewPerson

我尝试过类似的事情

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

来自API (4.2)

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/

相关文章:

php - Laravel 广播 auth 路由简单地返回 "true"

php - 将 Laravel 5.2 部署到共享主机子域

php - Laravel 尝试将数据传递给 View 时 undefined variable

php - 如何通过laravel中的外键检索记录的完整数据?

php echo 无法打印

php - 检查字符串以查看文件是否存在于本地

php - 触发器 - 在插入另一表时更新一个表中的列

PHP fgetcsv() 没有读取所有行

php - 从 Laravel Pivot 返回计算的自定义属性

laravel - 为什么我的 updateOrInsert 不工作 laravel