I created four models: Item, ItemOption, ItemSize, ItemColor. My intention is to create an online shop, I want to have an online shop, say I create an article shirt, then I can add many variables (options) of that same shirt, particulary colors, sizes... each option with it's own stock. I set these models with a hasManyThrough relationship but then I get this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'item_colors.item_option_id' in 'on clause' (SQL: select `item_colors`.*, `item_options`.`item_id` as `laravel_through_key` from `item_colors` inner join `item_options` on `item_options`.`id` = `item_colors`.`item_option_id` where `item_options`.`item_id` in (1))
These are my migrations:
Schema::create('item_options', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('item_id')->index()->nullable();
$table->foreign('item_id')->references('id')->on('items')->nullable();
$table->unsignedInteger('item_size_id')->index()->nullable();
$table->foreign('item_size_id')->references('id')->on('item_sizes')->nullable();
$table->unsignedInteger('item_color_id')->index()->nullable();
$table->foreign('item_color_id')->references('id')->on('item_colors')->nullable();
$table->timestamps();
});
Schema::create('items', function (Blueprint $table) {
$table->increments('id');
$table->string('image')->nullable();
$table->string('title');
$table->decimal('finalPrice', 5,2);
$table->text('body');
$table->timestamps();
});
Schema::create('item_colors', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('colorCode');
$table->timestamps();
});
Schema::create('item_sizes', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->timestamps();
});
And my models:
class Item extends Model
{
protected $table = 'items';
public function options()
{
return $this->hasMany(ItemOption::class);
}
public function sizes()
{
return $this->hasManyThrough(ItemSize::class, ItemOption::class);
}
public function colors()
{
return $this->hasManyThrough(ItemColor::class, ItemOption::class);
}
}
class ItemOption extends Model
{
protected $fillable = ['item_id', 'item_color_id', 'item_size_id', 'stock'];
public function color()
{
return $this->belongsTo(ItemColor::class);
}
public function size()
{
return $this->belongsTo(ItemSize::class);
}
}