2017-10-16 40 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是關係名。