简体   繁体   中英

Laravel Eloquent - Does the relation having the relation?

I have a model Alpha which has many model Beta which has many model Charlie I wan't all the beta from one alpha which have at least one charlie.

So my guess was :

$alpha = Alpha::first();
$betasWithACharlie = $alpha->betas()->has('charlies')->get();

But this doesn't work. I also tried with "whereHas" unsuccessfully.

Simply:

$betasWithACharlie = $alpha->betas()->has('charlies', '>', 1)->get();

Or you can retrieve 'charlies' only if they fulfill a certain condition for more advanced queries

$betasWithACharlie = $alpha->betas()->whereHas('charlies', function($query){
$query->where('condition');
})->get();

I have a thought that i don't test before:

$betasWithACharlie = $alpha->betas()->whereHas('charlies', function ($query) {
    $query->where('beta_id', '!=', 0);
})->get();

And try another one:

$betasWithACharlie = Alpha::whereHas('betas', function ($query) {
    $query->has('charlies');
});

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