Triple backticks (```) wrapping the code please
Laravel Eloquent Query, is this too complex?
Ok so, here is a little background of my db: - Products Table (price, discount, category_id ...) - Categories Table (image_path) - Products Languages Table (description, title, language_id) - Categories Languages Table (category name, language_id) I've done it in this way because this web app supports multiple languages. In the snippet down below I am getting the product information, and the category in which this product is in information, in the language in which the locale is set in the moment of the query. I am getting the results I want, but do you think there could be a more optimized way of doing it?
$products_sale = ProductDifferentLang::whereHas('language',function ($q){
$q->where('slug', app()->getLocale());
})
->whereHas('product', function($q){
$q->where('product_discount', '>', '0');
})
->with('product.images')
->with('product.category.CategoryDifferentLang', function($q){
$q->whereHas('language', function ($q){
$q->where('slug', app()->getLocale());
});
})->latest()->take(10)->get();
MORE INFO: CategoryDifferentLang is the model for 'Products Languages Table' and ProductDifferentLang is the model for ' Categories Languages Table'
@Kris01 okay, so IMHO a JOIN would make sense - you are going to make a Product instance using columns from both tables. Let's start simply:
$products_sale = Product::query()
->selectRaw('products.*, local_products.title, local_products.description')
->leftJoinSub(
ProductLanguage::join('languages', 'languages.id', '=', 'product_languages.language_id')->where('languages.slug', app()->getLocale()),
'local_products',
fn (JoinClause $join) => $join->on('products.id', '=', 'local_products.product_id');
)
->where('product_discount', '>', '0')
->latest()
->take(10)
->get();
Now you have a Collection of 10 Product instances each with a title and description attribute in the specific locale.
Please or to participate in this conversation.