Sorting by a translation field (ie, title)

Hi everyone, I feel like I must be missing something simple (as usual) or am making something overly complicated when trying to sort a query by my title translation field. I have a Product model that is linked to my Brand model via a brand_id field, with the relationship in the Product model as follows:
public function brand()
{
return $this->belongsTo(\App\Models\Brand::class);
}
public function brand()
{
return $this->belongsTo(\App\Models\Brand::class);
}
When I try to get the Products for a Particular brand, things start breaking. I had this query, but it breaks things on the front end, the id field gets overridden and breaks the relationships to translations, I can't use slugs, etc.
$brandProducts = Product::where('brand_id', '=', $brand->id)
->join('product_translations', 'product_id','=', 'products.id', 'inner')
->orderBy('title', 'asc')->get();
$brandProducts = Product::where('brand_id', '=', $brand->id)
->join('product_translations', 'product_id','=', 'products.id', 'inner')
->orderBy('title', 'asc')->get();
I feel like I am doing something obviously wrong here and I shouldn't have to keep adding more and more JOINs to get the fields I need to make this work properly. I suspect that I'm still relatively new to Laravel may be coming into play here as well. Is there an easier way to query using a field (brand_id) and still have access to sorting via some of the "default" Repository associations like translations and slugs?
2 Replies
Hro
Hro2y ago
GitHub
GitHub - Astrotomic/laravel-translatable: A Laravel package for mul...
A Laravel package for multilingual models. Contribute to Astrotomic/laravel-translatable development by creating an account on GitHub.
daniel
danielOP2y ago
awesome, well that makes the sorting a lot easier. i still seem to "lose" slug data on the frontend for some reason oh weird, i think i've found the issue these product entries and translations were created programmatically, and the actual product_translations rows are still set to active=false which i think is breaking some connections yeah, that was it. if i set active=1 for the translations and slug fields manually, everything starts showing up as expected
Want results from more Discord servers?
Add your server