【问题标题】:How can I insert both ID of Two tables (Many to Many Relationship)如何插入两个表的 ID(多对多关系)
【发布时间】:2019-01-08 05:55:21
【问题描述】:

我有三个表 Category 和 Company 和 Company_category。

公司模式

public function categories(){
    return $this->belongsToMany(\App\Category::class);
}

类别模型

public function companies(){
    return $this->belongsToMany(Company::class,'company_category');
}

当我尝试将公司 ID 插入表中时

类别控制器代码:

$category = new Category();
$category->companies()->sync($request->get('company_id'));

如何同时插入 category_id 和 company_id 只有这段代码返回错误:

SQLSTATE[23000]:违反完整性约束:1048 列“category_id”不能为空(SQL:插入company_categorycategory_idcompany_id)值(,1))

【问题讨论】:

  • 先保存$category,这样就有ID了
  • 在category表的迁移表中make category_id->nullable()试试
  • @haffisasma 我不希望 category_id 为空
  • 请输入你的外键是怎么做的
  • @Stormhammer 谢谢

标签: php laravel laravel-5.7


【解决方案1】:

就像@Stormhammer 提到的,您需要先保存类别,否则它没有 ID。

$category = new Category();
$category->save();
$category->companies()->sync($request->get('company_id'));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-23
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多