Defining Custom Intermediate Table Models In Laravel
In Many to Many relationship we create pivot table to join keys.
To learn more about Many to Many relationship visit our Bajarangisoft site.
Now Custom many-to-many pivot models should extend the Illuminate\Database\Eloquent\Relations\ Pivot
class while custom polymorphic many-to-many pivot models should extend the Illuminate\Database\Eloquent \Relations\MorphPivot
class.
For Example(1)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class products extends Model
{
/**
* The users that belong to the role.
*/
public function users()
{
return $this->belongsToMany('App\categories')->using('App\Product_Categories');
}
}
When defining the Product_categories
model, we will extend the Pivot
class:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product_Categories extends Model
{
//
}
You can combine using
and withPivot
in order to retrieve columns from the intermediate table. For example, you may retrieve the created_by
and updated_by
columns from the Product_categories
pivot table by passing the column names to the withPivot
method:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class products extends Model
{
/**
* The users that belong to the role.
*/
public function users()
{
return $this->belongsToMany('App\categories')
->using('App\Product_Categories')
->withPivot([
'created_by',
'updated_by',
]);
}
}
Pivot models may not use the SoftDeletes
trait. If you need to soft delete pivot records consider converting your pivot model to an actual Eloquent model.
Custom Pivot Models And Incrementing IDs
If you have defined a many-to-many relationship that uses a custom pivot model, and that pivot model has an auto-incrementing primary key, you should ensure your custom pivot model class defines an incrementing
property that is set to true
.
public $incrementing = true;