In Laravel and Eloquent you can use ManyToMany-Relations with a pivot table. The problem in my case is the automatic ID of the pivot row. Can I change how the ID is generated? I want to use UUIDs for that matter.
For other Objects you can just implement this behaviour in the Model, but there is no model for pivot objects.
Did I miss something?
Yeah, wherever you are adding new records to the pivot table, either through attach()
or sync()
, you give it a key/value array of additional items to put into the pivot table as the second parameter.
So for example $user->roles()->attach($role, array('id' => $uuid));
If you are doing this, it might be useful to also make sure your id
isn't set to auto increment.
It might also be important to note that a lot of people don't even have an id
column on their pivot table because it's usually not required unless you plan on creating a model for it, or it contains some other foreign key for some reason besides the 2 it would usually have.
I think creating Intermediate model does better job otherwise we will have to add primary uuid whenever we create new record.
use Webpatser\Uuid\Uuid;
use Illuminate\Database\Eloquent\Relations\Pivot;
class ProjectAssignee extends Pivot
{
public $incrementing = false;
protected $keyType = 'string';
protected $primaryKey = 'id';
protected $guarded = [];
public static function boot()
{
parent::boot();
self::creating(function ($model) {
$model->id = (string) Uuid::generate(4);
});
}
}
Now we can create attach easily
Project::first()->assignees()->attach(Assignee::inRandomOrder()->take(5)->pluck('id')->toArray());
Don't forget to chain using
method to tell relationship about intermediate table.
public function assignees(){return $this->belongsToMany(
Assignee::class,
'projects_assignees',
'project_id',
'assignee_id')
->using(ProjectAssignee::class);}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With