Jazzy
Jazzy

Reputation: 6129

Laravel 4.1 Eloquent using "where" with "with" to filter the related MySQL table

Attempting to emulate a LEFT JOIN using Eloquent and receiving an error. Basically, I am trying to get Users with addresses, but only of a certain type.

This code does not work, but I think you will get the gist:

$user = User::with('addresses', 'cards')->where(function($query) {
    $query->where('address.type', '=', 'shipping');
})->find(Auth::user()->id);

If I leave off the where it works fine, but more addresses returned than I need/want.

How can I make it so I only get addresses with a type = 'shipping'? I might want to do the same thing with cards as well. If there are no shipping addresses, I still want everything else.

I was trying to use Eloquent vs Fluent/DB (which I did make work), but just can't figure it out.

Follow-up: Depending on what version of PHP you have, you may need to do array(load array) vs. [load array]. Dev and Prod are not always the same.

Upvotes: 0

Views: 171

Answers (2)

SillasSoares
SillasSoares

Reputation: 382

This way will return your User with all their cards and only addresses where type = 'shipping'

$user = User::with(['cards','addresses'=>function($query){
      $query->where('type','shipping');
    }])->find(Auth::user()->id);

Upvotes: 0

lagbox
lagbox

Reputation: 50491

You can try something like

$user = Auth::user();
$user->load(['cards', 'addresses' => function($q) {
    $q->where('type', 'shipping');
}]);

Eager Loading - Constraints / Lazy Eager Loading

Upvotes: 1

Related Questions