简体   繁体   English

Laravel 多对多关系与附加数据透视表

[英]Laravel many-to-many relationship with additional pivot data

I am having a users table:我有一个users表:

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:然后是user_roles表,定义如下:

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并存储actordirector等值

And a user_record pivot table:还有一个user_record数据透视表:

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 .所以,一个Record有很多User ,而这个Record有很多User_Role

All Ids in user_record are the foreign key to the respective fields. user_record中的所有 Id 都是相应字段的外键。

Is this called a hasManyThrough relationship and if so how does the user_roles() in User model look like?这是否称为 hasManyThrough 关系,如果是这样, User模型中的user_roles()是什么样的?

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

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.不,这里有一个典型的简单Many To Many关系,有两个表和包含两者的id的第三个数据透视表。

And the relation should contain both id 's instead like :并且关系应该包含​​两个id ,而不是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM