Bring Existing and Non-Existing Records

1

I have the following scene:

$consulta   = Dealer::find(1);

No Model

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

Then if I do:

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

It brings me all the services that the TEM concessionaire.

How can I use the same methodology to bring the services that the DO NOT HAVE concessionaire? That is, to simulate LEFT OUTER JOIN .

I need all records in the same query.

    
asked by anonymous 25.05.2016 / 14:16

1 answer

3

I'm noticing that you're using a hasMany from Dealer to DealerService. I think you will probably have a relationship for Dealer within DealerService .

So you can use the whereDoesntHave method 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 realize that the small difference is that this query should be done "out of the relationship."

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

    
25.05.2016 / 15:03