2014-10-20 50 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