Ad

Laravel Many-to-many Relationship With Additional Pivot Data

- 1 answer

I am having a users table:

CREATE TABLE `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `users_name_unique` (`name`)
) ;

and then user_roles table which is defined like this:

if (!Schema::hasTable('user_roles')) {
            Schema::create('user_roles', function (Blueprint $table) {
                $table->increments('id');
                $table->string('role');
                $table->timestamps();
                $table->softDeletes();
            });
        }

and stores values such as actor, director etc

And a user_record pivot table:

if (!Schema::hasTable('user_record')) {
            Schema::create('user_record', function (Blueprint $table) {
                $table->integer('record_id')->unsigned();
                $table->integer('user_id')->unsigned();
                $table->integer('user_role_id')->unsigned();
                $table->string('character_name');
                $table->integer('ranking');
            });
        }

So, one Record has many User which has many User_Role for this Record.

All Ids in user_record are the foreign key to the respective fields.

Is this called a hasManyThrough relationship and if so how does the user_roles() in User model look like?

public function user_roles()
{
    return $this->belongsToMany(UserRole::class, 'record_user', 'user_id', 'record_id');
}
Ad

Answer

No, you have got a typical simple Many To Many relationship here, with two tables and the third pivot that contains the id's of the both.

And the relation should contain both id's instead like :

public function user_roles()
{
    return $this->belongsToMany(UserRole::class, 'user_record', 'user_id', 'user_role_id');
    ______________________________________________^^^^^^^^^^^_______________^^^^^^^^^^^^
}
Ad
source: stackoverflow.com
Ad