Level 104
You need to extend the Pivot class for the custom Pivot Model class:
use Illuminate\Database\Eloquent\Relations\Pivot;
class AttributeSku extends Pivot
1 like
I have this simple structure:
Product model
lass Product extends Model
{
protected $table = 'products';
public function skus(): HasMany
{
return $this->hasMany(Sku::class);
}
public function attributes(): HasMany
{
return $this->hasMany(Attribute::class);
}
}
Attribute Model
class Attribute extends Model
{
protected $fillable = [
'name',
];
public const SIZE = 'size';
public const COLOR = 'color';
public const ATTRIBUTES = [
self::SIZE,
self::COLOR
];
public function skus(): BelongsToMany
{
return $this->belongsToMany(Sku::class)
->using(AttributeSku::class)
->withPivot('id', 'value');
}
public function product(): BelongsTo
{
return $this->belongsTo(Product::class);
}
public function scopeSize($query): void
{
$query->where('name', self::SIZE);
}
public function scopeColor($query): void
{
$query->where('name', self::COLOR);
}
}
SKU Model
class Sku extends Model
{
public function attributes(): BelongsToMany
{
return $this->belongsToMany(Attribute::class)
->using(AttributeSku::class)
->withPivot('id', 'value');
}
public function product(): BelongsTo
{
return $this->belongsTo(Product::class);
}
}
AttributeSKU model
class AttributeSku extends Model
{
protected $fillable = [
'attribute_id',
'sku_id',
'value',
];
protected $table = 'attribute_sku';
public function sku(): BelongsTo
{
return $this->belongsTo(Sku::class);
}
public function attribute(): BelongsTo
{
return $this->belongsTo(Attribute::class);
}
}
When I try to access the product model with relation ''skus.attributes'
$products = Product::with(['skus.attributes'])->get()
Call to undefined method App\Models\AttributeSku::fromRawAttributes()
Any idea why?
You need to extend the Pivot class for the custom Pivot Model class:
use Illuminate\Database\Eloquent\Relations\Pivot;
class AttributeSku extends Pivot
Please or to participate in this conversation.