Ryan
Ryan

Reputation: 1628

Can I join a related table using Lauravel/Eloquent eager loading?

I'm having trouble understanding how eager loading works with Lauravel/Eloquent. I'd like to grab all clients, do some stuff with them, and output their brand_name. I have these tables:

    Clients
+-------------------+
| Field             |
+-------------------+
| client_id         |
| client_name       |
| client_brand_id   |
+-------------------+

    Brands
+-------------------+
| Field             |
+-------------------+
| brand_id          |
| brand_name        |
+-------------------+  

In the client model I have the relationship:

public function brand()
{
    return $this->hasOne('Brand', 'client_brand_id', 'brand_id');
}

And inverse in the brands model:

public function clients()
{
    return $this->hasMany('Client', 'brand_id', 'client_brand_id');
}

I want to do this, but it doesn't work:

foreach( Client::with( 'brand' )->get( array('client_id', 'client_name' ) ) as $client ){
    echo $client->brand->brand_name;
}

Upvotes: 0

Views: 83

Answers (1)

lowerends
lowerends

Reputation: 5267

You need to define your brand relationship in your client model like this:

public function brand()
{
    return $this->belongsTo('Brand', 'client_brand_id', 'brand_id');
}

The reason is that you have a one-to-many relationship, not a one-to-one relationship between clients and brands.

Also, you need to get the complete model for the eager loaded relationship to be available, like so:

foreach( Client::with( 'brand' )->get() as $client )
{
    echo $client->brand->brand_name;
}

Upvotes: 1

Related Questions