Where not Exists en Laravel

Where not Exists en Laravel

任何人都可以告诉我我的 laravel 查询中可能有什么错误,基本上我想要的是列出一个 table 的记录,其 ID 在另一个 table 中不相关].我在 Mysql 中使用此查询完成了此操作:SELECT * FROM item WHERE NOT EXISTS (SELECT null FROM qualifications WHERE grades.item_id = item.id AND qualifications.user_id = 2);

但现在我需要在 laravel 中执行相同的查询,我是这样尝试的: codigo

我得到的是这个我不知道如何解决的语法错误: error

我非常感谢任何能告诉我我做错了什么,或者我在 Laravel 中以何种形式进行查询的人。

您也可以像

一样将查询重写为左连接
SELECT i.*
FROM item i
LEFT JOIN qualifications q ON q.item_id = i.id  AND q.user_id = 2
WHERE q.item_id IS NULL

在查询生成器中,您可以将其写为

DB::table('item as i')
    ->select('i.*')
    ->leftJoin('qualifications as q', function ($join) use($user_id) {
        $join->on('q.item_id', '=', 'i.id')
             ->on('q.user_id', '=', $user_id);
    })
    ->whereNull('q.item_id')
    ->get();

我建议您使用的另一种方法是设置您的关系和模型,并使用 eloquent 方式

class Item extends Model
{
    public function qualifications()
    {
        return $this->hasMany(\App\Models\Qualification::class, 'item_id');
    }
}

class Qualification extends Model
{
    public function qualifications()
    {
        return $this->belongsTo(Item::class, 'item_id');
    }
}

然后你可以使用Querying Relationship Absence

Item::whereDoesntHave('qualifications', function ($query) use($user_id) {
    $query->where('user_id', '=', $user_id);
})->get();