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
You need to swap the hasOne with BelongsTo and vice versa;
Company.php
public function users()
{
return $this->belongsTo(User::class, 'user_id');
}
public function address()
{
return $this->belongsTo(Address::class);
}
User.php
public function company()
{
return $this->hasOne(Company::class);
}
Address
public function company()
{
return $this->hasOne(Company::class);
}
and then in Controller
Company::whereHas('users')
->whereHas('address')
->with('users')->with('address')
->get();
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.