Skip to content
Advertisement

How to get all data from a Eloquent Model with it’s relations?

My question is how to get the data from an eloquent model with its relation?

Imagine 3 tables:

users:

| id | name | email           |
|----|------|-----------------|
| 1  | name | email@email.com |

companies:

| id | name | user_id | address_id |
|----|------|---------|------------|
| 1  | name | 1       | 1          |

addresses:

| id | zip    | state |
|----|--------|-------|
| 1  | 101010 | LA    |

And the relations:

Company.php

public function user()
{
    return $this->hasOne(User::class);
}

public function address()
{
    return $this->hasOne(Address::class);
}

User.php

public function company()
{
    return $this->belongsTo(Company::class);
}

Address.php

public function company()
{
    return $this->belongsTo(Company::class);
}

In this case how I can get let’s say all the companies with their related users and addresses?

on Company::whereHas('users')->get(); getting:

Illuminate/Database/QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.company_id' in 'where clause' (SQL: select * from `users` where `users`.`company_id` in (1, 2, 3, 4, 5))'

Any thoughts?

Thank you

Advertisement

Answer

The issue was that in the company model, the user and the address methods were referencing with the hasOne() method to other models. It was looking for a secondary key to be in the users’ table, not in the companies one.

Simply swapping up the hasOne() with belongsTo fixed out my issue.

So now my Company.php model looks like:

public function user()
{
    return $this->belongsTo(User::class);
}

public function address()
{
    return $this->belongsTo(Address::class);
}

User.php

public function company()
{
    return $this->hasOne(Company::class);
}

Address.php

public function company()
{
    return $this->hasOne(Company::class);
}

Now we can get all the list of companies with their user and address by Company::with('user')->with('address')->get();

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement