以下是我的表具有多对多关系,group_user作为中间表。
| users | groups | group_user |
-------------------------------------------
| id | id | group_id |
| name | name | user_id |
| created_at| creator_id | created_at |
| updated_at| created_at | updated_at |
| | updated_at | |
groups.creator是用户表引用的用户ID。
当我尝试查询组表时,它会返回这样的内容。
[{"id":1,"name":"Akatsuki","creator":1,"created_at":"2015-10-13 12:22:20","updated_at":"2015-10-13 12:22:20"}]
我想要的是当我查询groups表时,它还返回创建者的用户数据,如hasOne关系。
在用户模型中
public function groups()
{
return $this->belongsToMany('App\Group')->withTimestamps();
}
在组模型中
public function users()
{
return $this->belongsToMany('App\User')->withTimestamps();
}
答案 0 :(得分:0)
在查询组后,我只是覆盖了group_creator列。
foreach($available as $data) {
$data['group_creator'] = User::find($data['group_creator']);
}
现在它返回
[{"id":1,"group_name":"Akatsuki","creator":{"id":1,"firstname":"John","lastname":"Doe","created_at":"2015-10-13 12:19:35","updated_at":"2015-10-13 14:14:41"},"created_at":"2015-10-13 12:22:20","updated_at":"2015-10-13 12:22:20"}]
连同用户详细信息。