A pivot table stores the relationship between two entities in a many-to-many relationship.
Example:
users
teams
team_user
-------
user_id
team_id
joined_at
Migration:
Schema::create('team_user', function (Blueprint $table) {
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->foreignId('team_id')->constrained()->cascadeOnDelete();
$table->timestamp('joined_at')->nullable();
$table->primary(['user_id', 'team_id']);
});
Access pivot data:
$user->teams->first()->pivot->joined_at;
When extra business logic/data exists, I may create a custom pivot model.
Scenario
For a subscription-like relationship:
user_id
plan_id
started_at
expires_at
status
The pivot is no longer just a simple linking table—it contains business information.
0 comments:
Post a Comment
Thanks