Reputation: 7110
I need to implement model for table with only two foreign keys. In my db I have tables like this:
product (id_product, ...)
category_to_product (FK id_category, FK id_product)
category (id_category, ...)
How to manage this connections in Laravel? Should I implement model for merge table and how it may looks? category_to_product
table does not represent entity(/model) and have only design-relation property.
Database Migrations
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');
});
Products
Schema::create('products', function(Blueprint $table)
{
$table->increments('id_product');
// ...
});
Categories
Schema::create('categories', function(Blueprint $table)
{
$table->increments('id_category');
// ...
});
Upvotes: 2
Views: 3831
Reputation: 5133
Do the following:
In the model Category:
public function products(){
return $this->belongsToMany('Category');
}
In the model Product:
public function categories(){
return $this->belongsToMany('Category', 'category_to_product');
}
In the model CategoryToProduct:
public function categories() {
return $this->belongsTo('Category');
}
public function products() {
return $this->belongsTo('Product');
}
Note the naming of these methods! Those are the same as the DB-table names. See ChainList's answer.
Upvotes: 1
Reputation: 1208
@pc-shooter is right about creating methods.
But you still have to create the pivot table with your migration first
Schema::create('products', function(Blueprint $table)
{
$table->increments('id')
$table->string('name');
}
Schema::create('categories', function(Blueprint $table)
{
$table->increments('id')
$table->string('name');
}
Then your pivot table
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
}
Upvotes: 3