2

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

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
4

3 回答 3

3

形成 laravel github问题

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

你最好手动做

$table->unsignedInteger('attachable_id')->nullable();
$table->string('attachable_type')->nullable();
于 2019-09-16T09:42:35.540 回答
1

attachable_idAttachment模型中的可填充数组中使用。

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

注意:确保表中的 attachable_id 可以为空。

于 2019-09-16T09:49:54.283 回答
0

您需要fillable在模型上指定属性

class Attachment extends Model
{
      //only the field names inside the array can be mass-assign
      protected $fillable = ['attachable_id']; 
}

更多细节:Laravel 中的“Mass Assignment”是什么意思(链接


在您的迁移中,您可以这样做以使该列可以为空:

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

->nullable()指定该列允许 NULL 值(链接

于 2019-09-16T10:01:00.897 回答