2014-10-20 53 views
0

我定義爲一個雄辯的ORM的關係如下:Laravel Eloquent ORM急切加載。關係不正確地返回空

ProductConfiguration

​​

產品

public function productConfigurations() 
    { 
     return $this->hasMany('Excel\Products\ProductConfiguration'); 
    } 
    public function productType() 
    { 
     return $this->belongsTo('Excel\Products\ProductType'); 
    } 

我希望如果我做了以下我將加載指定產品類型的所有產品配置,以及相關產品的嵌套ed產品類型詳細信息和產品配置貨幣

$results = ProductConfiguration::with(
      array(
       'product' => function($query) use ($product_type) { 
         $query->where('product_type_id' , $product_type); 
        }, 
       'product.productType', 
       'currency' 
      ) 
     ) 


      ->get(); 

但是,返回的集合將'product'設置爲NULL。貨幣關係在那裏,但產品關係不是。我可以看到輸出的SQL查詢和選擇產品,如果我直接粘貼到我的SQL編輯器

select * from `products` 
where `products`.`id` in ('12', '13') 
and `product_type_id` = '1' 

我是正確地認爲該查詢的結果應包括在檢索正確的產品查詢我的收藏,還是在我的思想中有一些明顯的缺陷?

+0

發生什麼,如果你刪除''' 'product.productType''''和它添加到你'''' product''''功能:'' '$查詢 - >與( 'productType')'''?希望有所幫助。 – ArjanSchouten 2014-10-20 09:40:09

+0

同樣的結果。產品是NULL。它的奇怪,因爲正確的SQL quries正在運行,但結果並沒有出現在收集 – 2014-10-20 09:53:55

回答

0

我認爲你不想實現這一點。現在你得到的是ProductConfigurationproducts,只有certain_type

所以如果你有一些其他類型的配置product你會得到null,因爲你從product有限的結果只有一個具有某種產品類型的結果。

我可能是錯的,但您可能想要得到屬於Product的那些ProductConfiguration,它是certain_type的類型。在這種情況下,你應該使用whereHas

$results = ProductConfiguration:: 
      with('product', 'product.productType', 'currency')-> 
      whereHas('product', function($q) use ($product_type) 
      { 
      $q->where('product_type_id', '=', $product_type); 

      })->get(); 
+0

斑點。更有效的查詢 – 2014-10-20 11:13:46

1

我恨張貼此作爲一個答案,但因爲我沒有足夠的代表處發表評論所以先試試這個:

$results = ProductConfiguration::with('product')->get(); 

dd($results->toArray()); 

看看你會得到什麼,如果你得到一些數據,試試這個

$results = ProductConfiguartion::with(array('products' => function($query){ 
    $query->where('product_type_id' , $product_type); 
})->get(); 

dd($results); 

看到你得到了什麼,如果你得到null:你的$ product_type變量可能是你沒有想到的東西,所以請嘗試dd($ product_type)以確保它符合你的期望。

+0

良好的故障排除技術。我肯定有某種緩存問題,因爲我把它分解成了你列出的步驟並且工作。我一點一點地放回剝離出來的部分,直到我留下原始查詢並保持正常工作。 – 2014-10-20 10:42:37