Reputation: 235
I have a question with laravel relationship OneToMany. My database have 2 table product and product_entry. Product will have infomation to choose same price... and product_entry will have infomation about infomation.
1 Product have have many product_entry will another language. But site only 1 language in the same time, so have anyway i only choose product_entry have product_entry_language same current language?
Ex: i have 1 product a with language "en" and "es". Normal, current language is "en". In blade, i must foreach product->product_entries and if(product_entry_language == "en") { ** get Info **} => I want don't need run foreach
Model
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'];
}
Upvotes: 4
Views: 964
Reputation: 15971
You can do this by
Product::with(['entries' => function ($q) {
$q->where('product_entry_language', \App::getLocale());
}])->get();
\App::getLocale()
is the current laravel locale
Upvotes: 4
Reputation: 163938
Use a constraint, for example:
Product::with(['product_entry' => function ($q) use($language) {
$q->where('language', $language);
}])->get();
Where product_entry
is relationship name.
Upvotes: 1