samedi 20 juillet 2019

Laravel Eloquent query order_by hasOne() parameter, then later by updated_at

I have a right now simple $ads query, but I need to add more complexity to it for a richer ordering result.

I have an index() method at AdsController, so I list a lot of ads ordered by last updated date. So, I need to order it first by a linked model called promo.promotype (which goes from 1 to 4 values), then later order by the updated_at parameter in Ad Model.

This is the actual query:

        $query = Ad::query();
        $query->where('category_id', $sub_category->category_id)->with(['description', 'resources', 'category.description', 'category.parent.description', 'promo', 'stats']);

        //Bunch of conditions here? ...

        //Minimal Price
        if (null !== Input::get('min_price')) {
            $query->when(request('min_price') >= 0, function ($q) {
                return $q->where('price', '>=', request('min_price', 0));
            });
        }


        //Maximum Price
        if (null !== Input::get('max_price')) {
            $query->when(request('max_price') >= 0, function ($q) {
                return $q->where('price', '<=', request('max_price', 0));
            });
        }


        //Order
        $query->orderBy('updated_at', 'desc');

        $ads = $query->get();

So, I need to order results first from the promotype column at AdPromo Model (set as hasOne in Ad Model)

I need these results:

ads.poromotype = 4 (random between them)
ads.poromotype = 3 (random between them)
ads.poromotype = 2 (random between them)
ads.poromotype = 1 (random between them)
ads.poromotype = null (orderred by updated_at)

This has a big importance for me, but I just don't know hoy to achieve, thanks!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire