duannai5858 2017-06-21 07:12
浏览 51
已采纳

Laravel - SQLSTATE [23000]:完整性约束违规:1452无法添加或更新子行:外键约束失败

I am building a project in Laravel on trying to persist a record in the database for the model Content that I have set up like this:

class Content extends Model
{
    /**
     * The attributes that are guarded by mass assignable.
     *
     * @var array
     */
    protected $guarded = [
        'id'
    ];

    public function contentType()
    {
        return $this->hasOne('App\ContentType');
    }
}

In my controller I am first saving the record in the content_types table like this:

    public function resolveType($type)
    {
        return ContentType::firstOrCreate(
          ['name' => $type,
          'slug' => str_slug($type, '-')]
        );
    }

And then I am saving the content:

        Content::create([
          'ct_id' => $post->ID,
          'cms_id' => '',
          'title' => $post->post_title,
          'slug' => str_slug($post->post_title, '-'),
          'excerpt' => $post->post_excerpt,
          'body' => $this->formatBodyImages($post->post_content),
          'password' => $post->post_password,
          'parent_id' => $post->post_parent,
        ]);

The ContentType model is set up like this:

class ContentType extends Model
{
    /**
     * The attributes that are guarded by mass assignable.
     *
     * @var array
     */
    protected $guarded = [
        'id'
    ];

    public function contents()
    {
        return $this->hasMany('App\Content', 'ct_id');
    }
}

So, when I try to persist new content record, I get the error:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (middleton.contents, CONSTRAINT contents_ct_id_foreign FOREIGN KEY (ct_id) REFERENCES content_types (id)) (SQL: insert into contents (cms_id, title, slug, excerpt, body, password, parent_id, updated_at, created_at)

  • 写回答

1条回答 默认 最新

  • duanpeng1532 2017-06-21 07:26
    关注

    Looks like $post->ID is empty and there is ContentType with specified ID in the DB. Maybe you're trying to do this?

    'ct_id' => $post->id,
    

    You can check contents of the $post variable with dd($post) command.

    If $post->id gives you correct value (it's not empty and it exists in the table), then try to use fillable array with all listed properties of using guarded array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)