我想将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();
时,我得到{}
的{{1}}作为响应。
响应示例:
category_id
答案 0 :(得分:2)
您的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');
}
答案 1 :(得分:0)
您应该将关系与渴望加载的属性分开。
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->categories()->pluck('id');
}
public funvtion 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 funvtion categories()
{
return $this->hasMany(AdSeatCategories::class);
}
}
在控制器中执行:
$seats = Seat::with('categories:id')->get();