[英]Select all records where a relationship count is zero using Eloquent?
In plain English: I have three tables. 简而言之:我有三个桌子。
subscription_type
which has many email_subscription
s which has many email
s. 具有许多
email_subscription
的subscription_type
具有许多email
的。
I'm trying to select all email_subscription
records that have a particular subscription_type
, that also don't have any associated email
records that have a status
of Held
. 我正在尝试选择所有具有特定
subscription_type
email_subscription
记录,这些记录也没有任何处于Held
status
的关联email
记录。
The particular bit I am stuck on is only returning email_subscriptions
which have zero emails
(with an additional where clause stacked in there described above). 我所停留的特定位置只是返回
emails
为零的email_subscriptions
(上面描述了一个附加的where子句)。
Using Eloquent, I've been able to get a bit of the way, but I don't have any idea how to select all the records that have a relationship count of zero: 使用Eloquent,我已经有了一些办法,但是我不知道如何选择关系计数为零的所有记录:
$subscriptionsWithNoCorrespondingHeldEmail = EmailSubscriptions::whereHas('subscriptionType', function($q) {
$q->where('name', 'New Mission');
})-; // What do I chain here to complete my query?
Additionally, is this even possible with Eloquent or will I need to use Fluent syntax instead? 此外,Eloquent甚至可以做到这一点,还是我需要使用Fluent语法?
You can use the has()
method to query the relationship existence: 您可以使用
has()
方法查询关系是否存在:
has('emails', '=', 0)
Eg: 例如:
$tooLong = EmailSubscriptions::whereHas('subscriptionType', function($q) {
$q->where('name', 'New Mission');
})->has('emails', '=', 0)->get();
Edit 编辑
You can do more advanced queries with the whereHas()
and whereDoesntHave()
methods: 您可以使用
whereHas()
和whereDoesntHave()
方法进行更高级的查询:
$tooLong = EmailSubscriptions::whereHas('subscriptionType', function($q) {
$q->where('name', 'New Mission');
})
->whereDoesntHave('emails', function ($query) {
$query->where('status', '=', 'whatever');
})->get();
OK what I have under stand from your Question is you would like to have a All Emails which have 好吧,我对您的问题的理解是,您希望收到一封所有电子邮件,其中包含
specific subscription_type, Zero(0) association and status = status
特定的subscription_type,零(0)关联和状态=状态
If yes so you canuse array in where statement. 如果是,则可以在where语句中使用数组。 Like:
喜欢:
$q->->where(array('status' => 'status','subscription_type'=>'what ever you want));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.