2016-11-24 109 views
0

我試圖建立一個產品通過API更新的查詢。該應用程序構建在包裝在NodeJS圖層中的Angular2中。Laravel雄辯的關係查詢不起作用

產品與文件存在多對多關係。我想要發生的事情是,當數據發送到API來更新文件時,Eloquent查詢會檢查這個關係是否已經存在,如果不存在,它會將關係添加到'file_product'表中。我有這種功能正常工作與類別多對多的關係,但由於某種原因,這不適用於文件關係。這裏是我的代碼:

產品控制器更新功能:

public function update(Request $request, $id) 
    { 
     if($id && is_numeric($id)) { 
      try { 
       $requestProductVars = $request->get('product'); 
       $product = Product::find($id); 
       $product->title = $requestProductVars['title']; 
       $product->description = $requestProductVars['description']; 
       $product->images = json_encode($requestProductVars['images']); 
       $product->SKU = $requestProductVars['SKU']; 
       $product->manufacturer_id = $requestProductVars['manufacturer_id']; 
       $product->active = (($requestProductVars['active'] === true) ? '1' : '0'); 
       if($request->get('categories')) { 
        $categories = $request->get('categories'); 
        foreach($categories as $categoryId) { 
         $category = Category::find($categoryId); 
         if(!$product->categories->contains($category)) { 
          $product->categories()->save($category); 
         } 
        } 
       } 
       if(count($requestProductVars['files'])) { 
        $files = $requestProductVars['files']; 
        foreach($files as $file) { 
         $fileId = $file['id']; 
         $fileRecord = File::find($fileId); 
         if(!$product->files->contains($fileRecord)) { 
          $product->files()->save($fileRecord); 
         } 

        } 
       } 
       $product->save(); 

正如你所看到的,我檢查,看看是否有關於該請求的「文件」屬性,如果有我遍歷每個文件,獲取ID並檢查是否存在使用關係:

if(!$product->files->contains($fileRecord)) { 

files屬性包含一個File對象數組。

我的代碼似乎停在這裏,甚至似乎不執行如果。類代碼的功能在這段代碼中工作正常,雖然這很奇怪,我在這裏做的事情完全一樣。

我檢查了產品和文件以及許多一對多的關係模型被罰款這裏定義爲:

Product.php 

/** 
    * Returns all files associated with a product 
    * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany 
    */ 
    public function files() { 
     return $this->belongsToMany('App\File')->withTimestamps(); 
    } 

File.php

/** 
    * Returns all products related to a file 
    * 
    * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany 
    */ 
    public function products() { 
     return $this->belongsToMany('App\Product')->withTimestamps(); 
    } 

任何人都可以明白爲什麼我的代碼沒有按」 t似乎在工作?

感謝

回答

0

好吧,我發現了什麼問題。

在我將文件提取到產品功能之前,我在產品表中有一個名爲'files'的單元。我忘了刪除這個單元格,當我試圖查詢文件關係時,這導致衝突。希望這有助於未來的人。