Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Pivot table id column

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?

like image 883
Tobias Krischer Avatar asked Jul 03 '14 10:07

Tobias Krischer


2 Answers

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.

like image 93
user1669496 Avatar answered Oct 13 '22 18:10

user1669496


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);}
like image 26
Afraz Ahmad Avatar answered Oct 13 '22 17:10

Afraz Ahmad