laravel - Laravel Eloquent 几种关系
问题描述
我为示例制作了三个简单的模型(用户请求获取电话):
User
- ID
- 登录
Request
- ID
- 用户身份
- 电话号码
Phone
- ID
- 姓名
关系如下:
在用户模型中:
public function requests()
{
return $this->hasMany('App\Requests');
}
在手机型号中:
public function phoneRequests()
{
return $this->belongsTo('App\Requests');
// But it returns null
}
我需要从 User 模型开始收集一个集合,并获得所有请求的电话(我需要那里的名称)。问题是 phone_id 在请求模型中,而在文档中这是相反的。
我找不到任何关系来达到我的目标。
理想的情况是通过以下关系:
Auth::user()->requests->phoneRequests
// Would returns the phone name the user has requested
我也尝试使用原始 SQL 查询来实现,但我更愿意使用关系。这个怎么做 ?
解决方案
您的Requests
模型中应该有电话关系,如下所示:
public function phone()
{
return $this->belongsTo('App\Phone');
}
因此,现在您可以使用手机为用户获取所有请求,如下所示:
$user->requests->first()->phone; // this is for the first request, but you can get the phone for each request in a loop, I guess you know how to do that.
还要注意,您在 Phone 模型中的关系是错误的,因此是 null 的原因。那个应该再次 hasMany 就像在 User 中一样,因为根据您的表结构,电话可以有很多请求。
在你的Phone
模型中,你应该有这个:
public function requests()
{
return $this->hasMany('App\Requests', 'phone_id');
}
因为根据您的数据库结构,电话可以属于许多请求。
推荐阅读
- java - 如何使用 JavaEE eclipse 将我的 React Native 应用程序连接到 MySQL 数据库?
- javascript - 如何修复硬刷新/缓存干净刷新中没有加载的数据
- python - 如何使用 Python 中的数据集使用 PSO(粒子群优化)实现聚类?
- sql - 在使用“CASE”时,是否有任何功能可以减少我的查询大小
- react-native - 是否可以从 AsyncStorage 中删除所有项目
- java - 找不到数据源 JNDI
- javascript - 从 React 中的父 JSON 数据中获取所有子节点
- php - 图像未在 Laravel 中的正确位置上传
- reactjs - 反应道具与儿童。什么时候用?
- java - Apache Ignite SQL 查询结果差异