php - 如何使用带有 eloquent 和 laravel 的嵌套急切加载在另一个表中获取外键名称
问题描述
所以我目前有 3 个模型Specie
Type
User
。我希望能够获得与 Specie 模型相关的最后修改用户的名称
关系如下
Class Specie extends Model {
public function type()
{
return $this->belongsTo('App\Type', 'type_id');
}
public function user()
{
return $this->belongsTo('App\User', 'user_id');
}
}
Class Type extends Model {
public function specie()
{
return $this->hasMany('App\Specie', 'type_id');
}
}
Class User extends Model {
public function specie()
{
return $this->hasMany('App\Specie', 'user_id');
}
}
我试过这个
Class Specie extends Model {
public function lastModified()
{
return $this->belongsTo('App\User', 'last_modified_by');
}
}
然后使用下面的代码
$this->type->with(['specie.lastModified' => function ($query) use
($userId) {
$query->where('user_id', $userId);
}])->get();
不幸的是,这似乎不起作用
但是,通过使用此代码
$this->type->with(['specie' => function ($query) use ($userId) {
$query->where('user_id', $userId);
}])->get();
我能够得到这个:
"id": 1,
"type": "Halo",
"created_at": "2019-07-20 13:02:53",
"updated_at": "2019-07-20 13:02:53",
"specie": [
{
"id": 6,
"user_id": 1,
"type_id": 1,
"note": "et",
"last_modified_by": 1,
},
{
"id": 7,
"user_id": 1,
"type_id": 2,
"note": "sa",
"last_modified_by": 2,
},
]
但是,我想得到的是最后修改的人名的名字,它是 User 模型中的主键和 Specie 模型中的外键
这是我期望得到的:
"id": 1,
"type": "Halo",
"created_at": "2019-07-20 13:02:53",
"updated_at": "2019-07-20 13:02:53",
"specie": [
{
"id": 6,
"user_id": 1,
"type_id": 1,
"note": "et",
"last_modified_by": 1,
"user": [
{
"id": 1,
"user": 'gerrard'
}
]
},
{
"id": 7,
"user_id": 1,
"type_id": 2,
"note": "sa",
"last_modified_by": 2,
"user": [
{
"id": 2,
"user": 'chris'
}
]
}
]
解决方案
Awith()
里面with()
应该这样做:
$this->type->with(['specie' => function ($query) use ($userId) {
$query->where('user_id', $userId);
$query->with('lastModified');
}])->get();
唯一的区别是关系键不是命名"user"
的,而是关系的名称 ( "last_modified"
)。
"id": 1,
"type": "Halo",
"created_at": "2019-07-20 13:02:53",
"updated_at": "2019-07-20 13:02:53",
"specie": [
{
"id": 6,
"user_id": 1,
"type_id": 1,
"last_modified_by": 2,
"note": "et",
"last_modified": {
"id": 2
}
}
]
推荐阅读
- angular - 制作角度图像裁剪器功能
- insert - 插入语句内的表中的自动增量 ID
- python - 尝试重置密码时出现 Djongo + Django + MongoDB Atlas DatabaseError
- python - AssertionError: [101, 1203, 1365, 1137, 8601, 117, 4835, 1104, 1141, 1292, 119, 102, 0, 0, 0, 0, 0, 0, 0, 0] 不是
- c++ - 为什么复制初始化需要 C++17 中的析构函数并保证移动/复制省略?
- python - 创建 Pandas.Dataframe 时如何保持索引中的顺序
- javascript - 仅将 .map() 方法用于副作用是否合法?
- c# - ASP.NET MVC 5 - 使用带有或不带有 __RequestVerificationToken 的 ajax 将视图模型数组发布到控制器
- x86 - WinDbg:地址中的冒号是什么意思?
- mysql - 为什么 MySQL 会更改不同数据库中查询的联接类型