Laravel Eloquent:belongsToMany 返回字符串数组而不是对象数组

问题描述 投票:0回答:1

我有两个与数据透视表连接的表。

显示:

+----+--------+
| id | show   |
+----+--------+
|  1 | show1  |
|  2 | show2  |
|  3 | show3  |
+----+--------+

草稿类型:

+----+--------+
| id | type   |
+----+--------+
|  1 | type1  |
|  2 | type2  |
|  3 | type3  |
+----+--------+

显示草稿类型:

+---------+---------------+
| show_id | draft_type_id |
+---------+---------------+
|  1      | 1             |
|  1      | 2             |
|  1      | 3             |
+---------+---------------+

所以本质上,一个节目有许多不同的草稿类型,这是我在雄辩的节目中使用的关系:

public function draft_types()
{
    return $this->belongsToMany('App\Models\DraftTypes', 'show_draft_types', 'show_id', 'draft_type_id');
}

问题是每当我这样做时:

Shows::where('id', 1)->with(['draft_types'])->first()

我明白了:

{
    id: 1,
    show: "show1",
    draft_types: [
        {
            id: 1,
            type: "type1"
        },
        {
            id: 2,
            type: "type2"
        },
        {
            id: 3,
            type: "type3"
        }
    ]
}

我想要得到的是这个:

{
    id: 1,
    show: "show1",
    draft_types: [
        "type1",
        "type2",
        "type3"
    ]
}

有没有办法通过雄辩的关系做到这一点?

php laravel eloquent has-and-belongs-to-many eloquent-relationship
1个回答
0
投票

您可以向

Show
模型添加附加属性以及所需数组的访问器:

// Show.php

class Show extends Model
{
    protected $appends = ['draft_types_array'];

    public function draft_types()
    {
        return $this->belongsToMany('App\Models\DraftTypes', 'show_draft_types', 'show_id', 'draft_type_id');
    }

    public function getDraftTypesArrayAttribute()
    {
        return $this->draftTypes->pluck('type')->toArray();
    }
}

用途:


$show = Shows::where('id', 1)->with(['draft_types'])->first();

dd($show->draft_types_array);


// Outputs: 
// [
//   "type1",
//   "type2",
//   "type3"
//  ]

© www.soinside.com 2019 - 2024. All rights reserved.