2017-08-08 59 views
1

我想为新的和现有的对象使用表单部分。Laravel将关系对象添加到新的雄辩模型

我发现类似的问题:

,但我不能,不想保存的父对象。

我来自带活动记录的导轨视图。我能做到以下几点:

比方说,我有一个类别,它包括很多产品:

category = Category.new 
category.products << Product.new 

现在我可以通过产品迭代像

category.products.each do ... 

现在我想在laravel相同与一个雄辩的模型

$category = new Category(); 
$category->products()->.... 

add不存在的建设呃。 save需要存储类别 attach需要同样的

有没有办法让我的思想工作? 我的目标是使用部分相同的形式进行编辑并创建具有已定义关系的模型。

+0

所以要保存多个产品相同的类别ID? – madalinivascu

+0

@madalinivascu是的。但目录中的类别ID不存在于数据库中。这是一个新的类别,其中包括一些新产品 – rob

+0

所以首先创建类别,然后创建新产品 – madalinivascu

回答

1

您可以使用$category->products()->createMany([])Create Many

创造了许多作品,你有很多Product一个Category后,您可以循环在他们使用

for ($category->products as $product) { 
    // do something 
} 

$category->products->each(function ($product) { 
    // do something 
}); 

注缺乏()产品后,这将返回一个Collection

+0

它是否也适用于未存储在数据库中的新类别?我想验证并创建一个新的产品类别 – rob

+0

这是一个好主意,但不适合我的问题。 for createMany()我需要一个现有的类别。但目前这个类别不存在 – rob

0

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; 
    } 



}