Search code examples
joinlaraveleloquentfluent

Laravel Eloquent - include related columns in query results


Objective: Return a composite response from my query, containing columns from both related models using Eloquent so that I can use Form::model to restore field values for User values AND Addresses values in my view. I want all the data in a single object and I don't want to use compact or otherwise manipulate the data if I don't have to.

Tables:

users (id, userWorkAddressID, ...)

addresses (ID, ...)

Models

User

public function address()
{
    return $this->hasOne('Address', 'ID', 'userWorkAddressID');
}

Address

public function user()
{
    return $this->belongsTo('User', 'id', 'userWorkAddressID');
}

Things I've tried

$user = User::find($id);

This just returns user data - no address data

$user = User::find($id)->address

This just returns the address for the user, but no user data

$user = User::with('address')->find($id);

This returns the user data, no address data

$user = User::with(array('address' => function($query){
    $query->addSelect(array('id', 'addressLine1'));
}))->find($id);

This also returns only the user data, no address data

I could just use Fluent, but do I have to?

How can I use Eloquent to join those two tables and return a single object consisting of the fields I represent in my view?


Solution

  • First off your relations are wrong. Change both to:

    public function address()
    {
        return $this->hasOne('Address', 'userWorkAddressID', 'ID');
    }
    Address
    
    public function user()
    {
        return $this->belongsTo('User', 'userWorkAddressID', 'id');
    }
    

    then probably you will see the related model. Just remember to:

    1 Eager load the related model: `$user = User::with('address')->find($someId);

    2 use array notation for related model properties in the form: Form::model($user, ..) Form::text('address[city]', ...)