php - 插入具有一对多关系的数据

标签 php laravel eloquent

我有三个表:产品、公司、类型。公司和类型与产品具有一对多关系。 [类型模型]

class Type extends BaseModel {
    public static $table = "type";
    public static $timestamps = true;

    public function products() {
      return $this->has_many('Products');
    }
}

[公司模型]

class Company extends BaseModel {
    public static $table = "company";
    public static $timestamps = true;

    public function products() {
        return $this->has_many('Products');
    }
}

[产品型号]

class Products extends BaseModel {
    public static $table = 'products';
    public static $timestamps = true;


    public function company() {
        return $this->belongs_to('Company');
    }

    public function type() {
        return $this->belongs_to('Type');
    }
}

在 add_product route 我有

$product = new Products($new_product); 
$company_id = $all_posts['company_id'];
$company = Company::find($company_id);
$company->products()->save($product);
$type_id = $all_posts['type'];
$type = Type::find($type_id);
$type->products()->save($product);

但是当我尝试将数据插入数据库时​​,我得到:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '11' for key 'PRIMARY'

如何更新“产品”表中的 type_id 和 company_id?

最佳答案

如果我没记错的话,你的产品表应该有product_id和type_id列?只需指定这些值:

$new_product['company_id'] = $all_posts['company_id'];
$new_product['type_id'] = $all_posts['type'];
$product = new Products($new_product); 
$product->save();

您不需要使用公司和类型模型来建立它们与产品之间的关系。您只需填写 ids 即可。

关于php - 插入具有一对多关系的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14572279/

相关文章:

PHP 日期 : week numbers for 2015/2016

php - 通过浏览器访问 ftp 文件夹时是否可以创建自定义 View ?

php - 如何通过 git 推送 laravel 包和帮助文件

php - Laravel 4.2 artisan CLI 在 composer 更新后不再工作

php - SQLSTATE[42S22] : Column not found: 1054 Unknown column '' in 'where clause' (SQL: select * from `customer` where `` = 1 limit 1)

php - make :auth 后迁移 Laravel 时出错

php - WordPress 代码仅显示 1 个帖子

php - ElasticSearch Laravel侦察异常(exception)

php - 如何将此 Laravel PHP 代码简化为一个 Eloquent 查询?

php - 在 Laravel 中按投票计数对帖子进行排序