Where not Exists en Laravel

生来就可爱ヽ(ⅴ<●) 提交于 2020-08-25 07:54:12

问题


Could anybody tell me what error I might have in my laravel query, basically what I want is to list the records of a table whose id is not related in another table. I did it in Mysql with this query: SELECT * FROM item WHERE NOT EXISTS (SELECT null FROM qualifications WHERE grades.item_id = item.id AND qualifications.user_id = 2);

but now I need to do this same query in laravel, I tried it this way: codigo

and what I get is this syntax error that I do not know how to solve anymore: error

I am very grateful to anyone who can tell me what I am doing wrong, or in what form I make that query in Laravel.


回答1:


You can also rewrite your query as left join like

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

In query builder you can write it as

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

Another approach which i suggest you to go with, is setup your relations and models and do it with eloquent way

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');
    }
}

And then you can use Querying Relationship Absence

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


来源:https://stackoverflow.com/questions/50711923/where-not-exists-en-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!