首页 > 解决方案 > 如何从 Eloquent 模型中获取所有数据及其关系?

问题描述

我的问题是如何从一个雄辩的模型中获取数据及其关系?

想象3张桌子:

用户

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

公司

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

地址

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

和关系:

公司.php

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

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

用户.php

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

地址.php

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

在这种情况下,我怎样才能得到所有公司及其相关用户和地址?

Company::whereHas('users')->get();得到:

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))'

有什么想法吗?

谢谢

标签: phplaraveleloquentrelationship

解决方案


您需要将 hasOne 与 BelongsTo 交换,反之亦然;

公司.php

public function users()
{
    return $this->belongsTo(User::class, 'user_id');
}

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

用户.php

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

地址

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

然后在控制器中

Company::whereHas('users')
    ->whereHas('address')
    ->with('users')->with('address')
    ->get();

推荐阅读