Get all the eloquent models without attitude

I would like to get all the models that have no relationship.

Similar to a selection of models that have one:

return $this->model->has('quote')->orderBy('created_at', 'desc')->get(); 

I wish I had the opposite. I can't find the documentation to do this though.

Basically this query:

 SELECT * FROM custom_design_requests RIGHT JOIN quotes ON quotes.`custom_design_request_id` = `custom_design_requests`.id 

But I would like to avoid using Query Builder ( DB::table('custom_design_requests')->rightJoin('quotes', 'quotes.custom_design_request_id', '=', 'custom_design_requests.id')->get(); ), so I have a collection of model instances.

thanks

+5
source share
3 answers

You can try something like this:

 $this->model->has('quote', '<', 1)->orderBy('created_at', 'desc')->get(); 
+9
source

Try:

 return $this->model ->leftJoin('quotes', 'quotes.custom_design_request_id', '=', 'custom_design_requests.id') ->whereNull('quotes.custom_design_request_id') ->orderBy('created_at', 'desc')->get(); 

This will be LEFT JOIN your model with quotes and will only take those for which there are no corresponding quotes.

+1
source

I think this is better than the decision:

 $this->model->doesntHave('quote')->orderBy('created_at', 'desc')->get(); 

This is described in more detail here:

https://laravel.com/docs/5.4/eloquent-relationships#querying-relationship-absence

+1
source

All Articles