简体   繁体   中英

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.

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 .

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).

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:

$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?

You can use the has() method to query the relationship existence:

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:

$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

If yes so you canuse array in where statement. Like:

        $q->->where(array('status' => 'status','subscription_type'=>'what ever you want));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM