Мне нужно реализовать модель для таблицы только с двумя внешними ключами. В моей БД у меня есть такие таблицы:
product (id_product, ...)
category_to_product (FK id_category, FK id_product)
category (id_category, ...)
Как управлять этими связями в Laravel? Должен ли я реализовать модель для таблицы слияния и как она может выглядеть? category_to_product
Таблица не представляет сущность (/ модель) и имеет только свойство конструкторских отношений.
Миграция базы данных
CategoryToProduct
Schema::create('category_to_product', function(Blueprint $table)
{
$table->integer('id_category')->unsigned();
$table->foreign('id_category')
->references('id_category')
->on('categories')
->onDelete('cascade');
$table->integer('id_product')->unsigned();
$table->foreign('id_product')
->references('id_product')
->on('products')
->onDelete('cascade');
});
Товары
Schema::create('products', function(Blueprint $table)
{
$table->increments('id_product');
// ...
});
категории
Schema::create('categories', function(Blueprint $table)
{
$table->increments('id_category');
// ...
});
@ pc-shooter прав насчет создания методов.
Но вы все равно должны сначала создать сводную таблицу с вашей миграцией
Schema::create('products', function(Blueprint $table)
{
$table->increments('id')
$table->string('name');
}
Schema::create('categories', function(Blueprint $table)
{
$table->increments('id')
$table->string('name');
}
Тогда ваш сводный стол
Schema::create('category_product', function(Blueprint $table)
{
$table->integer('category_id')
$table->foreign('category_id')->references('id')->on('categories');
$table->integer('product_id');
$table->foreign('product_id')->references('id')->on('products');
// And finally, the indexes (Better perfs when fetching data on that pivot table)
$table->index(['category_id', 'product_id'])->unique(); // This index has to be unique
}
Сделайте следующее:
В модели категория:
public function products(){
return $this->belongsToMany('Category');
}
В модели Товар:
public function categories(){
return $this->belongsToMany('Category', 'category_to_product');
}
В модели CategoryToProduct:
public function categories() {
return $this->belongsTo('Category');
}
public function products() {
return $this->belongsTo('Product');
}
Обратите внимание на названия этих методов!
Это те же имена, что и в таблицах БД. Увидеть ChainList«s
ответ.