我有三个表:产品,公司,类型。公司和类型与产品有一对多的关系。 [型号]
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);
但是当我尝试将数据插入db时,我得到:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '11' for key 'PRIMARY'
如何更新Products表中的type_id和company_id?
答案 0 :(得分:2)
如果我没有错,你的product表应该有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();
您无需使用公司和类型模型来建立它们与产品之间的关系。你可以简单填写ID。