[英]How can I get all entities without a specific related entity?
I have these tables: 我有这些表:
users 用户
id
name
events 事件
id
name
entries 项
id
user_id
event_id
How can I get all users that do not have an entry with event_id
4? 如何获得所有没有event_id
4条目的用户?
With this code: 使用此代码:
$users = User::query();
$users->leftJoin('entries', 'users.id', '=', 'entries.user_id')
->where('event_id','!=', $event_id)->get();
I still get users that already have an entry for that specific event. 我仍然得到已经有该特定事件条目的用户。
This is what I want: 这就是我要的:
$entries = Entry::where(event_id, '=', 4)->get();
foreach ($entries as &$entry) {
//remove all entries from $entries array which "user_id = $entry->user_id"
}
How can I do the above with just a query? 仅凭查询我该如何做?
Going by your question following is the answer but i guess this is not what you finally want. 以下是您提出的问题的答案,但是我想这不是您最终想要的。 so elaborate more and specify the sample input and output datasets 进一步详细说明并指定样本输入和输出数据集
select * from your_table where event_id <> 4;
The SQL you want is: 您想要的SQL是:
select user_id
from t
group by user_id
having sum(event_id = 4) = 0;
select u.*
from User u
left join entries e
on e.user_id = u.id and e.event_id = 4
where e.id is null
You're looking for <>
, not !=
. 您在寻找<>
,而不是!=
。 Also you're not letting it know which table event_id
is on. 另外,您也不会让它知道哪个表event_id
处于打开状态。
Try 尝试
$users = User::query();
$users->leftJoin('entries', 'users.id', '=', 'entries.user_id')
->where('entries.event_id','<>', $event_id)->get();
More information can be found at https://laravel.com/docs/5.4/queries#where-clauses 可以在https://laravel.com/docs/5.4/queries#where-clauses中找到更多信息。
You can use the whereDoesntHave
builder method. 您可以使用whereDoesntHave
构建器方法。
$users = User::query()->whereDoesntHave("entry", function($q) use ($event_id) {
$q->where('id', $event_id);
})->get();
The method takes a closure in which you can define criteria for the related entities that must not exist. 该方法采用闭包形式,您可以在其中为必须不存在的相关实体定义条件。
If you need the users and the entries, I think you can still join the entries using with
. 如果您需要用户和条目,我认为您仍然可以使用with
加入条目。
$users = User::query()
->with('entries')
->whereDoesntHave("entry", function($q) use ($event_id) {
$q->where('id', $event_id); })
->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.