代码之家  ›  专栏  ›  技术社区  ›  fermoga

使Laravel中关系的唯一结果成为对象,而不是数组中的对象

  •  0
  • fermoga  · 技术社区  · 6 年前

    在数组内的对象中获取相关用户结果的查询

    $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 回复  |  直到 6 年前
        1
  •  2
  •   sumit    6 年前

    改变

    $this->hasMany(Users::class, "id", "user_id") 
    

    $this->hasOne(Users::class, "id", "user_id")
    
        2
  •  0
  •   Prashant Prajapati    6 年前

    下面的代码将返回集合,因为它有许多关系

     $this->hasMany(Users::class, "id", "user_id"); 
    

    确保正确给出关系。 如果您的要求是单用户,请使用以下代码:

    $this->hasOne(Users::class, "id", "user_id");