Laravel: 创建 morphs() 关系可为空

Laravel: Create morphs() relationship nullable

我想创建一对一的多态关系允许空关系。

示例:

  Schema::create('ps_assistances', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('assistance_number', 50)->nullable();
            $table->morphs('assitanceable')->nullable();
  });

但是这个例子 return 在将“->nullable()”赋给变形列时为 null。

我尝试手动创建 _type 和 _id,但效果很好。

手动变形列的示例:

  Schema::create('ps_assistances', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('assistance_number', 50)->nullable();
            $table->string('assitanceable_type')->nullable();
            $table->unsignedBigInteger('assitanceable_id')->nullable();
  });

我想知道是否存在更好的方法来实现一对一多态关系可为空。

nullableMorphs 应该会为您处理这个问题

例如:

Schema::create('ps_assistances', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('assistance_number', 50)->nullable();
    $table->nullableMorphs('assitanceable');
});

您可以使用nullableMorphs

$table->nullableMorphs('assitanceable');

https://laravel.com/docs/9.x/migrations#column-method-nullableMorphs