【问题标题】:Inserting data with one-to-many relationship插入具有一对多关系的数据
【发布时间】:2013-01-12 09:30:31
【问题描述】:

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

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 路线中

$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'

如何同时更新 Products 表中的 type_id 和 company_id?

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    如果我没记错的话,你的 products 表应该有 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();
    

    您不需要使用 Company 和 Type 模型来建立它们与产品之间的关系。您可以简单地填写 id。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-20
      • 2016-10-15
      • 2011-07-21
      • 1970-01-01
      • 2013-06-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多