【问题标题】:Laravel 5.8 polymorphic relation `nullableMorphs` not workingLaravel 5.8多态关系`nullableMorphs`不起作用
【发布时间】:2020-01-17 02:54:15
【问题描述】:

我有一个附件表,它与其他表具有多态关系。我想在文件选择上上传一个文件并将其插入到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

【问题讨论】:

  • 如果有适合您的答案,请将您的问题标记为已回答。

标签: laravel laravel-5.8 polymorphic-relationship


【解决方案1】:

形成 laravel github issues:

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

你最好手动做,

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

【讨论】:

  • @jones 您是否直接在数据库中检查该字段是否标记为可为空?
  • 在我的数据库中,它的默认值为 null
  • @jones 那么你怎么得到Field 'attachable_id' doesn't have a default value。因为这是来自数据库的错误。
  • 知道了,我的 test_db 没有更新,因为我暂时评论了RefreshDatabase,并且迁移的新更改不受影响。我检查了开发数据库改变了,但测试数据库没有,并找到了原因。
  • @jones 如果您手动执行此操作,请检查您引用的 Id 是 unsignedBigIntegerunsignedInteger
【解决方案2】:

Attachment 模型的可填充数组中使用attachable_id

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

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

【讨论】:

    【解决方案3】:

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

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

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


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

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

    ->nullable()指定列允许NULL值(Link

    【讨论】:

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