Ad
Laravel Many-to-many Relationship With Additional Pivot Data
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
Related Questions
- → I can't do a foreign key, constraint error
- → How to implement DbDongle::convertTimestamps as workaround of invalid timestamps with MySql strict
- → MySQL error "Foreign key constraint is incorrectly formed"
- → Eloquent Multitable query
- → "Laravel 5.1" add user and project with userId
- → Database backup with custom code in laravel 5 and get the data upto 10 rows from per table in database
- → Laravel 5.1 QueryException when trying to delete a project
- → Using Array in '->where()' for Laravel Query Building
- → Chaining "Count of Columns" of a Method to Single Query Builder
- → Laravel Eloquent Joining Strange query
- → convert time using mysql laravel 5
- → How to update a column after an expiration date in MySQL?
- → Foreign key constraint fails on existing key
Ad