Laravel不存在的地方 [英] Where not Exists en Laravel
问题描述
有人可以告诉我我的laravel查询中可能有什么错误,基本上我想要列出的是ID与另一个表无关的表的记录.我使用以下查询在Mysql中完成了此操作:SELECT * FROM不存在的项目(SELECT等级为空,而grades.item_id = item.id和qualifications.user_id = 2)
但是现在我需要在laravel中执行相同的查询,我以这种方式尝试了它: codigo
我得到的是这个语法错误,我不知道该如何解决了:错误
我非常感谢能告诉我我做错了什么,或者我在Laravel中以哪种形式进行查询的人.
您也可以像
一样将查询重写为左连接 SELECT i.*从项目我左联接资格q ON q.item_id = i.id AND q.user_id = 2q.item_id为NULL的位置
在查询构建器中,您可以将其编写为
DB :: table('item as i')->选择('i.*')-> leftJoin('qualification as q',qualities 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();
我建议您使用的另一种方法是建立关系和模型,并雄辩地做到这一点
class项目扩展模型{公共职能资格{返回$ this-> hasMany(\ App \ Models \ Qualification :: class,'item_id');}}班级资格扩展模型{公共职能资格{返回$ this-> belongsTo(Item :: class,'item_id');}}
然后您可以使用查询关系缺失
Item :: whereDoesntHave('qualifications',function($ query)use($ user_id){$ query-> where('user_id','=',$ user_id);})-> get();
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.
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();
这篇关于Laravel不存在的地方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!