2017-10-16 53 views
2

我有一个关于laravel关系的问题OneToMany。我的数据库有2个表产品和product_entry。产品将有信息选择相同的价格...和product_entry将有关于信息的信息。Laravel - 选择孩子在哪里参数

1产品有很多product_entry会另一种语言。但网站只有1种语言在同一时间,所以无论如何,我只选择product_entry有product_entry_language相同的当前语言?

例如:我有1个产品与语言“EN”和“ES”。正常,当前的语言是“en”。在刀片,我必须的foreach产品 - > product_entries如果(product_entry_language == “EN”){**获取信息**} =>我想并不需要运行的foreach

型号

class Product extends Model 
{ 
    use TransformableTrait; 

    protected $table = 'product'; 
    protected $fillable = ['product_code','product_id']; 

    public function entries() 
    { 
     return $this->hasMany('App\Entities\ProductEntry', 'product_entry_product_id', 'product_id'); 
    } 

} 

class ProductEntry extends Model 
{ 
    use TransformableTrait; 
    protected $table = 'product_entry'; 
    protected $fillable = ['product_entry_product_id','product_entry_name']; 

} 

enter image description here

+0

也请发表您的机型。 –

+0

我已添加模型 –

回答

2

您可以通过

Product::with(['entries' => function ($q) { 
    $q->where('product_entry_language', \App::getLocale()); 
}])->get(); 

\App::getLocale()做到这一点是当前laravel区域

0

使用constraint,例如:

Product::with(['product_entry' => function ($q) use($language) { 
    $q->where('language', $language); 
}])->get(); 

哪里product_entry是关系名。