在模型中的appending属性中加载

nmpmafwu  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(412)

我想附加 category_id 进入 seat 集合,但我需要使用渴望加载或关系填充它。
我哪里做错了?
座椅型号:

class Seat extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public $appends = ['category_id'];

    protected $fillable = [
        'seat_name',
        'seat_url',
        'logo_src',
    ];

    public function getCategoryIdAttribute()
    {
        return $this->hasMany(AdSeatCategories::class);
    }

}

当我跑的时候 Seat::all(); ,我明白了 {} 为了 category_id 作为回应。响应示例:

{
"id": 95,
"seat_name": "gtest",
"seat_url": "http://ooop.com",
"logo_src": null,
"category_id": {},
},
lokaqttq

lokaqttq1#

应该将关系与属性分离。

class Seat extends Model
{
   public $appends = ['category_id'];

   /**
    * The attributes that are mass assignable.
    *
    * @var array
    */
    protected $fillable = [
        'seat_name',
        'seat_url',
        'logo_src',
    ];

    public function getCategoryIdAttribute()
    {
        return $this->categories()->pluck('id');
    }

    public function categories()
    {
        return $this->hasMany(AdSeatCategories::class);
    }

}

一个更好的解决方案使用的关系 categories 在模特的召唤下 Seat .

class Seat extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

    protected $fillable = [
        'seat_name',
        'seat_url',
        'logo_src',
    ];

    public function categories()
    {
        return $this->hasMany(AdSeatCategories::class);
    }

}

在控制器中:

$seats = Seat::with('categories:id')->get();
t40tm48m

t40tm48m2#

它看起来像你的 getCategoryIdAttribute() 是返回一个关系,当您希望它返回集合时,请务必调用 get() 这样地:

public function getCategoryIdAttribute()
{
    return $this->hasMany(AdSeatCategories::class)->get();
}

或者,您可能需要一个关系和一个属性:

public function categories()
{
    return $this->hasMany(AdSeatCategories::class);
}

public function getCategoryIdsAttribute()
{
    return $this->categories()->get()->pluck('id');
}

相关问题