yayuj
yayuj

Reputation: 2464

Eager Loading with where

I want to list all the garages by the car id, but the way I'm doing still returning informations about garages even if the car isn't found, the opposite happen, instead of nothing return, the garages returns with the car relations as empty.

Let me put in an example:

$garages = Garages::with(['cars'])->get();

This way I have everything, and I can't use ->where('car_id', 1) because the table garage doesn't have the car_id column. The only way I found was like this:

$garages = Garages::with(['cars' => function($q) { return $q->where('car_id', 1); }])->get();

The problem is that even if the car isn't found still returning data from garage and I don't want that because I want to use @forelse in blade and as it still returning data the @empty never works, and I get errors saying that I'm trying to get properties from a non-object (of course, cars doesn't exist if wasn't found).

Is there a way to use where and return data only if it was found?

@edit - The relations

class Users extends Eloquent
{
    public function cars()
    {
        return $this->hasMany('cars');
    }

    public function garages()
    {
        return $this->hasManyThrough('garages', 'cars', 'garage_id', 'garage_id');
    }
}

class Garages extends Eloquent
{
    public function cars()
    {
        return $this->hasMany('cars');
    }
}

class Cars extends Eloquent
{
    public function users()
    {
        return $this->belongsTo('users');
    }

    public function garages()
    {
        return $this->belongsTo('Garages');
    }       
}

Upvotes: 4

Views: 80

Answers (2)

NULL
NULL

Reputation: 1858

You can use this.

$garages = Garages::with(['cars' => function($q) { $q->where('car_id', 1); }])
                    ->whereHas('cars', function($q) { $q->where('car_id', 1); })
                    ->get();

Update: I have found another way to do this..

$garages = Garages::has('cars')
                    ->with(['cars'])
                    ->get();

Upvotes: 2

lukasgeiter
lukasgeiter

Reputation: 152850

I think you're going all wrong about this. If you need the garages of one car why not find the car and get all the garages using the relationship?

$user = User::find(1);
$garages = $user->garages;

foreach($garages as $garage){
    // just an example, you'll have to use your real properties
    echo 'Address: ' . $garage->address;
    echo 'Name: '. $user->name;
}

Upvotes: 2

Related Questions