Bring Existing and Non-existent Records

Asked

Viewed 51 times

1

I got the next thing:

$consulta   = Dealer::find(1);

No Model

# Serviços
public function dealer_servicos(){
    return $this->hasMany('App\DealerService', 'id_concessionaria');
}

So if I do:

@foreach($consulta->dealer_servicos as $value => $res)
   {!! $res->servico !!}
@endforeach

Brings me all the services that the dealership HAS.

It has as I use the same methodology to bring the services that the concessionaire HAS NOT ? That is, to simulate the LEFT OUTER JOIN.

I need all the records in the same query.

1 answer

3


I’m realizing you’re wearing one hasMany from Dealer to Dealerservice. I believe you will probably have a relationship to Dealer inside DealerService.

So you can use the method whereDoesntHave to do this.

$dealer = Dealer::find(1);

$dealerServices = DealerService::whereDoesntHave('dealers', function ($query) use($dealer)
{
        $query->where(['id' => $dealer->id]);

})->get();

If you notice, you will notice that the small difference is that this query should be made "out of the relationship".

Expressing in words, the method whereDoesntHave is intended to make a "When Dealerservice has no relationship with Dealer id 1".

  • But he will bring everyone in the same consultation ?

  • Yes, but if you want to use the Paginate you have no problem

  • I’ll test it, if you don’t bring it all I’ll go up to MG and punch you in the middle of your mouth.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.