【问题标题】:Why last id is lost while creating process?为什么创建进程时会丢失最后一个 ID?
【发布时间】:2019-11-13 21:20:50
【问题描述】:

我有一个可以正常工作的 create 方法,但尝试创建它的关系却失败了:

public function create(array $article, string $note)
{
    $art = $this->article->create($article);

    print($art->id) // this line is for helping me to know if id is successfully generated. It works!

    $this->article->note()->create([
        'article_id' => $art->id, // the id desapears
        'note'       => $note
    ])
}

控制台日志:

违反完整性约束:1048 列“article_id”不能为空(SQL:插入notesarticle_idnoteupdated_atcreated_at)值(?,TESTING,2019-11- 13 13:03:07, 2019-11-13 13:03:07))"

【问题讨论】:

  • 什么返回 dd($art);?

标签: laravel eloquent


【解决方案1】:

article_id 字段可能不是 Note 模型上的 fillable attribute

您也可以像这样创建注释,而不添加 article_id 作为可填充属性:

$art->note()->create([
    'note' => $note
]);

还要确保在模型上正确定义关系。如果一篇文章可以有很多注释,那么您的定义可能有问题,因为 note 目前是单数。如果它是一对一的关系,一切可能都很好。

【讨论】:

    【解决方案2】:

    您需要保存您的文章。 $art->save()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-10
      • 1970-01-01
      • 1970-01-01
      • 2010-12-09
      • 2017-01-22
      • 2013-12-31
      • 2021-10-23
      • 1970-01-01
      相关资源
      最近更新 更多