我获取相关用户的查询会导致数组内的对象
$members = CalendarMembers::with("user")
->where('calendar_id', $calendar[0]->calendar_id)
->get();
有这种关系
public function user()
{
return $this->hasMany(Users::class, "id", "user_id");
}
,结果是
"status": "200",
"success": true,
"data": [
{
"member_id": 4,
"calendar_id": 4,
"invited_by": null,
"color": "#7D96E1",
"role": "parent",
"added_at": "2018-02-07 09:06:49",
"user": [
{
"id": 4,
"name": "User Name",
"email": "username@gmail.com",
"first_name": "User",
"last_name": "Name",
"status": "active",
"is_activated": 0,
"created_at": "2018-02-07 09:06:49",
"updated_at": "2018-02-07 09:06:49"
}
]
},
但它总是一个User
,因此我尝试将user
更改为一个简单的对象:
"status": "200",
"success": true,
"data": [
{
"member_id": 4,
"calendar_id": 4,
"invited_by": null,
"color": "#7D96E1",
"role": "parent",
"added_at": "2018-02-07 09:06:49",
"user": {
"id": 4,
"name": "User Name",
"email": "username@gmail.com",
"first_name": "User",
"last_name": "Name",
"status": "active",
"is_activated": 0,
"created_at": "2018-02-07 09:06:49",
"updated_at": "2018-02-07 09:06:49"
}
},
但找不到解决方案却没有成功。
答案 0 :(得分:2)
更改
$this->hasMany(Users::class, "id", "user_id")
到
$this->hasOne(Users::class, "id", "user_id")
答案 1 :(得分:0)
以下代码将返回集合,因为它具有hasMany relation
$this->hasMany(Users::class, "id", "user_id");
确保正确给出关系。 如果您的要求是单个用户,请使用以下代码:
$this->hasOne(Users::class, "id", "user_id");