【问题标题】:Laravel Nova Polymorphic many-to-many relationship is not workingLaravel Nova 多态多对多关系不起作用
【发布时间】:2019-02-19 04:09:11
【问题描述】:

我正在使用 Laravel Nova 开发一个 Laravel 管理仪表板。我在使用多态多对多关系时遇到问题。以下是我的场景。

我有这个定义的用户表

class User extends Model
{
    public function sportsocieties()
    {
        return $this->morphedByMany(SportSociety::class, 'involvable', 'involvables', 'user_id', 'involvable_id');
    }

    public function dancersocieties()
    {
        return $this->morphedByMany(DancerSociety::class, 'involvable', 'involvables', 'user_id', 'involvable_id');
    }
}

这是 SportSociety 模型类

class SportSociety extends Model
{
    public function users()
    {
        return $this->morphToMany(User::class, 'involvable', 'involvables', 'involvable_id','user_id');
    }
}

这是 DancerSociety 模型班

class DancerSociety extends Model
    {
        public function users()
        {
            return $this->morphToMany(User::class, 'involvable', 'involvables', 'involvable_id','user_id');
        }
    }

然后我创建了一个迁移来创建数据透视表。这是迁移文件的定义。

class CreateInvolvablesTable extends Migration
{
    public function up()
    {
        Schema::create('involvables', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();

            $table->unsignedInteger("user_id");
            $table->unsignedInteger("involvable_id");
            $table->string("involvable_type");
        });
    }
    public function down()
    {
        Schema::dropIfExists('involvables');
    }
}

在 Nova UI 中,当我将 SportSociety 或 DancerSociety 附加到用户时,我收到以下错误消息。

Field involvable_type does not have a default value. (SQL: insert into involvables (user_id, involvable_id) values (1, 5))

我的多态关系有什么问题?还是 Nova 存在多态关系的问题?

【问题讨论】:

    标签: laravel eloquent laravel-nova


    【解决方案1】:

    问题是我没有为 Nova 使用正确的字段。在 Nova 中,我使用的是BelongsToMany。取而代之的是,我需要使用MorphToMany

    【讨论】:

      【解决方案2】:
      Field involvable_type does not have a default value. (SQL: insert into involvables (user_id, involvable_id) values (1, 5))
      

      这个错误意味着在数据库中这个字段没有default value('',NULL,你需要什么),你只需要将它设置为可空或传递一个值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-08
        • 2019-02-02
        • 2015-03-04
        • 2017-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多