【发布时间】:2016-02-15 13:18:55
【问题描述】:
在保存条目之前,我有一个 3 列的唯一限制要检查。
在我的例子中,product_id、product_attribute_id 和 product_option 值的条目是唯一的。
例如产品 1234 Size L 应该只有一个条目,1234 Color Orange 应该只有一个条目。
当我在测试中加倍输入“1-7-Fuscha Baby”时,我会正确收到错误
Integrity constraint violation:
1062 Duplicate entry '1-7-Fuscha Baby' for key 'p_a_v'
(SQL: insert into `product_options` (`product_attribute_id`, `value`, `product_id`, `updated_at`, `created_at`)
values (1, Fuscha Baby, 7, 2016-02-15 13:06:27, 2016-02-15 13:06:27))
所以现在我需要绕过创建该条目
在 ProductOption 模型上,我重写了 save 方法来添加检查。这是破坏的部分,无法弄清楚正确的语法。
public function save()
{
// before save code - Check for a unique value....
//
$product_option = ProductOption::where('product_id', $this->product_id)
->where('value' ,$this->value)
->where('product_attribute_id',$this->product_attribute_id)
->first()
;
if($product_option)
{
//i have the constraint violation, now how do I tell laravel to use $product_option instead of $this?
//return $product_option; messy error 1
//return $product_option->id; messy error 2
//$this = $product_option; sytnax error
//return; I think this works with the plain old save() call, but not for saveMany()
//$this->exists = true; //works for save(), fails for saveMany()
}
parent::save();
// after save code
}
此外,这应该适用于 saveMany 调用:
public function saveOptionsArray($product_options)
{
/*
$product_options = [
['name' => 1, 'value' =>'Pink'],
['name' => 'Color', 'value' =>'Yellow'],
['name' => 'Color', 'value' =>'Yellow'], //constraint violation
['name' => 'Size', 'value' =>'1'],
['name' => 'Size', 'value' =>'2'],
['name' => 'Size', 'value' =>'3'],
];
*/
$options = [];
foreach ($product_options as $product_option)
{
$option = new ProductOption();
$option->product_attribute_id = $product_option['name'];
$option->value = $product_option['value'];
//$option = $option->checkBeforeSave(); //same as the save() pre-check above.. didn't work out too well
$options[] = $option;
}
return $this->options()->saveMany($options);
}
【问题讨论】: