【问题标题】:Make an unique result from a relationship in Laravel be an object instead of an object within an array使 Laravel 中关系的唯一结果成为对象而不是数组中的对象
【发布时间】:2018-07-18 12:39:22
【问题描述】:

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

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

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

【问题讨论】:

    标签: php arrays laravel object relationship


    【解决方案1】:

    改变

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

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

    【讨论】:

    • 我忽略了hasOne,该死的。谢谢。
    【解决方案2】:

    下面的代码将返回具有 hasMany 关系的集合

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

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

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

    【讨论】:

      猜你喜欢
      • 2020-09-08
      • 2021-08-13
      • 2017-04-10
      • 2015-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-06
      • 2020-01-10
      相关资源
      最近更新 更多