php - 如何从 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))'
有什么想法吗?
谢谢
解决方案
您需要将 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();
推荐阅读
- c# - 限制映射到现有目标对象
- javascript - 古腾堡
返回 ReactJS '元素类型无效' - git - 通过 SSH 转发 HTTP 客户端证书
- java - 如何在maven多模块项目中构建依赖模块
- airflow - 气流 - 如果任一失败则运行任务
- php - 'Tymon\JWTAuth\Middleware\GetUserFromToken' 在哪里
- java - 为什么我的链接在测试期间需要双击,但手动单击?
- apache - 无法在一个 dockerfile 中安装带有闪亮应用程序的 apache+php
- vb.net - 逐个字符地手动编辑 PDF 的 Unicode 字符映射
- excel - 如何使用officejs在excel中显示范围选择输入对话框