Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return multiple relationships with Laravel Eloquent?

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

  • country
  • device
  • computer
  • category

I have created a table for each of these above 'things'. Similar 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 are associated with the corresponding table's ID.

What I want is do an Eloquent Query and search for all the users and 'replacing' 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 tacke this issue?

like image 658
Radical_Activity Avatar asked Jul 23 '16 17:07

Radical_Activity


2 Answers

$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

like image 148
Andrew Nolan Avatar answered Nov 14 '22 07:11

Andrew Nolan


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

Check out the documentation for eager loading multiple relationships.

like image 22
Daniel Avatar answered Nov 14 '22 06:11

Daniel