Laravel 5.8多态关系`nullableMorphs`不起作用

Laravel 5.8多态关系`nullableMorphs`不起作用,laravel,laravel-5.8,polymorphic-relationship,Laravel,Laravel 5.8,Polymorphic Relationship,我有一个附件表,它与其他表具有多态关系。我想在文件上上载一个文件,选择并将其插入到附件表中,但在创建父记录之前,此记录与任何父表都不相关,因此对于这两个字段可附加\u id,和可附加\u类型应为空。 以下是附件表迁移: schema::table('attachments', function (Blueprint $table) { $table->nullableMorphs('attachable'); }); 但是当我创建附件记录时,它显示了一个错误 $attachment

我有一个附件表,它与其他表具有多态关系。我想在文件上上载一个文件,选择并将其插入到
附件
表中,但在创建父记录之前,此记录与任何父表都不相关,因此对于这两个字段
可附加\u id
,和
可附加\u类型
应为空。 以下是附件表迁移:

schema::table('attachments', function (Blueprint $table) {
  $table->nullableMorphs('attachable');
});
但是当我创建附件记录时,它显示了一个错误

$attachment = new Attachment();
$attachment->name = 'name';
.........
.........
$attachment->save();

"message": "SQLSTATE[HY000]: General error: 1364 Field 'attachable_id' doesn't have a default value
表格:laravel github:

这只是定义变形id和变形类型列的最简单情况的帮助。如果您需要更多控制,可以单独分配它们

你最好是手动操作

$table->unsignedInteger('attachable_id')->nullable();
$table->string('attachable_type')->nullable();

附件
模型的可填充数组中使用
可附加的\u id

class Attachment extends Model
{
    protected $fillable = ['attachable_id'];
}

注意:确保表内可附加的\u id可为空。

您需要在模型上指定
可填充的属性

class Attachment extends Model
{
      //only the field names inside the array can be mass-assign
      protected $fillable = ['attachable_id']; 
}
更多细节:在Laravel()


在迁移过程中,可以执行以下操作以使列为空:

public function up()
{
    Schema::create('tablename', function (Blueprint $table) {
        $table->increments('attachable_id')->nullable();
    });
}

->nullable()null@jones那么如何获取
字段“attachable\u id”没有默认值
。因为这是数据库中的一个错误。明白了,我的测试数据库没有更新,因为我已经注释了
RefreshDatabase
,迁移的新更改不受此影响。我已检查开发数据库是否已更改,但测试数据库未更改,并找到了原因。@jones如果您是手动执行此操作,请检查您引用的ID是否为
unsignedBigInteger
unsignedInteger
。如果有任何答案,请将您的问题标记为已回答。