Radical_Activity
Radical_Activity

Reputation: 2738

How to return multiple relationships with Laravel Eloquent?

I have a table called users. Each of these users has different things:

I have created a table for each of these above 'things'. Similar to the following:

1 | United States
2 | United Kingdom
3 | Australia
4 | Canada
5 | Italy

etc...

I'm storing these values in the users' table as follows:

ID | Country | Device | Computer | Category |
---|---------|--------|----------|----------|
1  |       3 |      2 |        6 |        2 |
2  |       4 |      3 |        9 |        1 |

etc...

Now each of the above numbers is associated with the corresponding table's ID.

What I want is to do an Eloquent Query and search for all the users and 'replace' their corresponding values from their helper table.

I was thinking about doing a hasOne() Eloquent relationship for each of those things in the users table, but then I'm not sure how to get/call them at once.

Anyone can help me tackle this issue?

Upvotes: 12

Views: 69398

Answers (2)

Andrew Nolan
Andrew Nolan

Reputation: 2107

$model = Model::with('relatedModel', 'relatedModelTwo')->get();

So in your case, it can be something like this. If you only want one relations returned with the user, remove the others.

$user = User::with('country', 'Device', 'Computer', 'Category')->get();

When you dd($user), you should see the related models in the relations array attribute.

To access the relations' properties from there, it is simply

$user->device->deviceAttribute

Edit For Comment:

Eloquent will assume the foreign key uses the Model name. So if your user table has the id column, it assumes there will be a column on device table called user_id. If you did this, then you are set and nothing should have to be done.

If you named your column to relate the models something else, you will need to pass that through as a second argument in the relation method.

public function device()
{
    return $this->hasOne('App\Device', 'foreign_key_here',);
}

Inversely, if you wanted to get the user the device belongs to, Eloquent will attempt to match the user_id column on the device table to the id column on the user table. As before, if you used a different column to related them, declare the foreign key as the second argument.

public function user()
{
    return $this->belongsTo('App\User', 'foreign_key_here',);
}

Laravel Doc One-To-One Relation

Upvotes: 33

Daniel
Daniel

Reputation: 533

You're looking for this: $books = App\Book::with('author', 'publisher')->get();

Check out the documentation for eager loading multiple relationships.

Upvotes: 1

Related Questions