首页 > 解决方案 > Laravel,数据透视表与多对多关系冲突

问题描述

嘿伙计们,所以我正在使用 spatie 二进制 uuid 包,我几乎没有怀疑到目前为止所做的事情:User.php 迁移:

 public function up()
  {
    Schema::create('users', function (Blueprint $table) {
        $table->uuid('uuid');
        $table->primary('uuid');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
 }

角色迁移只有一个名为“name”的基本字段,带有时间戳

数据透视表:role_user

public function up()
{
    Schema::create('role_user', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('role_id')->unsigned()->nullable()->index();
        $table->uuid('user_uuid');

    });
}

我知道这是非常错误的,我不知道该怎么做,我正在尝试通过此调用保存角色模型

$uuid = '478d7068-ae64-11e8-a665-2c600cf6267b';
$model = User::withUuid($uuid)->first();
$model->roles()->save(new Role(['name' => 'Admin']));

它不起作用,我哪里出错了?我认为这与 role_user 迁移有关

用户.php

public function roles()
{
    return $this->belongsToMany(Role::class);
}

标签: laravellaravel-5eloquentuuid

解决方案


试试这个,枢纽迁移:

public function up()
{
    Schema::create('role_user', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('role_id')->unsigned()->nullable()->index();
        $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
        $table->uuid('user_uuid');
       $table->foreign('user_uuid')->references('uuid')->on('users')->onDelete('cascade');
    });
}

角色关系:

public function roles(){
  return $this->belongsToMany(Role::class,'role_user','user_uuid','role_id');
}

如果它不起作用,请告诉我


推荐阅读