you say you have many Lang records per product. how do you decide which is the proper one?
How to get only one result from hasMany relationship
Hi everyone, In my ecommerce I have a Product Model I use to deal with the products of the shop. This ecommerce is multilingual and I also have a ProductLang Model to deal with the translations of all products in all languages. I have these relationships:
//Product Model
public function lang()
{
return $this->hasMany('App\ProductLang');
}
//ProductLang Model
public function product()
{
return $this->belongsTo('App\Product');
}
I have a controller where I get my products and pass the data todo the view
$products=Product::where('stock', '>', 0)
->where('active', '=', 1)
->get();
In order to get the data I need from $products->lang I have to do a loop and then only use one of the result but I think this is not the best way to deal with it. I would like to know if there is any way to get the translation data I need when I get the products. How can I improve my code to get products and their proper translation in only one query? is it posible?
@ncarreno Try with scope on App\ProductLang like...
public function scopeCurrent($query)
{
return $query->whereLang(\App::getLocale())->first();
}
Then you can access it like $product->lang()->current() this will always return Model || null
The other solution is to set Accessor on App\Product like
public function getLanguage($lng = null)
{
$lng = $lng ?: \App::getLocale();
return $this->lang()->whereLang($lng)->first();
}
//Optional you can set
$appends = ['language'];
There is more options but you'll get the idea ;)
Please or to participate in this conversation.