Ken的答案并不适合我的特殊情况。所以我必须创建一个服务对象来照顾所有的依赖案例。此服务对象存储父级(我的类别)并为每个父级存储孩子(每个类别的产品)。当所有数据都有效时,它将会保存到数据库中。如果没有,那么save()返回false,我得到异常消息和验证错误。
所以我的服务对象包含以下内容:
namespace App\Services;
use Illuminate\Support\Facades\Validator;
class FormObject
{
protected $children = [];
protected $parent, $validator;
protected $errorMessages = [];
public function save(){
if(!$this->isValid()){
return false;
}
try{
DB::beginTransaction();
// save parent and all relations....
DB::commit();
}catch(\Exception $e){
DB::rollBack();
$this->addErrorMessage($e->getMessage());
return false;
}
return true;
}
public function isValid(){
return $this->getValidator()->passes();
}
public function add($identifier, array $collection){
$this->children[$identifier] = $collection;
}
public function addErrorMessage($message){
array_push($this->errorMessages, $message);
}
public function setParent(Model $parent){
$this->parent = $parent;
}
public function setValidator(Validator $validator){
$this->validator = $validator;
}
public function get($identifier){
return $this->children[$identifier];
}
public function getErrorMessages(){
return $this->errorMessages;
}
public function getParent(){
return $this->parent;
}
public function getValidator(){
return $this->validator;
}
}
来源
2017-08-08 09:21:08
rob
所以要保存多个产品相同的类别ID? – madalinivascu
@madalinivascu是的。但目录中的类别ID不存在于数据库中。这是一个新的类别,其中包括一些新产品 – rob
所以首先创建类别,然后创建新产品 – madalinivascu