【问题标题】:Eager loading inside appending property in model渴望在模型的附加属性中加载
【发布时间】:2018-09-24 10:16:00
【问题描述】:

我想将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(); 时,我得到{} for category_id 作为响应。 响应示例:

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

【问题讨论】:

  • 首先,您在accessor 中定义relationship,这些需要分开。其次,你们的关系表明seat 可以有很多categories。你们的关系是one to one 还是one to many
  • 了解您的预期关系很重要,因为这将决定您是返回类别数组还是单个类别 ID。

标签: php mysql laravel eloquent eager-loading


【解决方案1】:

看起来您的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');
}

【讨论】:

    【解决方案2】:

    您应该将关系与属性预加载分开。

    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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-08
      • 1970-01-01
      • 1970-01-01
      • 2012-06-16
      • 1970-01-01
      • 1970-01-01
      • 2013-05-30
      • 2013-05-06
      相关资源
      最近更新 更多