从Laravel中的关系中获取一个独特的结果,而不是数组中的对象

时间:2018-02-08 03:32:06

标签: php arrays laravel object relationship

我获取相关用户的查询会导致数组内的对象

$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"
            }
    },

但找不到解决方案却没有成功。

2 个答案:

答案 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");