【发布时间】:2020-01-04 04:41:12
【问题描述】:
所以我目前有3个模型SpecieTypeUser。我希望能够获得与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": 5,
"user_id": 1,
"type_id": 1,
"note": "et",
"created_by": 1,
"last_modified_by": 1,
}
]
但是,我想得到的是最后修改人名的名字,它是User 模型中的主键和Specie 模型中的外键
这是我期望得到的:
"id": 1,
"type": "Halo",
"created_at": "2019-07-20 13:02:53",
"updated_at": "2019-07-20 13:02:53",
"specie": [
{
"id": 5,
"user_id": 1,
"type_id": 1,
"note": "et",
"created_by": 1,
"last_modified_by": 1,
"last_modified_name": 'gerrard'
}
]
【问题讨论】:
-
你没有lastModified的型号??
-
LastModified 不是模型
-
所以首先创建这个模型并在模型中定义你的表名..ok
-
没有表lastModified... Specie表有2个外键
user_id和last_modified_bylast_modified_by的值是来自用户模型的用户id...用户模型有一个名字,所以我想得到那个用户的名字。请再读一遍问题
标签: php mysql laravel laravel-5 eloquent