skip to Main Content

I would like to order listing_data based on listing_packages.order . Here is the query

ListingData::with(['listing_package'])->orderBy('listing_package.order','desc')->paginate(24);

I would like to order based on listing_package.order "DESCENDING"

However, it returns

SQLSTATE[42S22]: Column not found: 1054 Unknown column
‘listing_package.order’ in ‘order clause’

Here is the model ListingData.php

public function listing_package(): BelongsTo
{
    return $this->belongsTo(ListingPackage::class);
}

Here is the model for ListingPackage.php

public function listing_data(): HasMany {
    return $this->hasMany(ListingData::class);
}

Edit:

I also try this one

    $relations = [
        'district',
        'regency',
        'province',
        'category',
        'type',
        'rentType',
        'listing_package' => function ($q){
            $q->orderBy('order','DESC');
        },
    ];
    $listings = ListingData::with($relations)
    ->latest()
        ->paginate(24);

But the data is not sorted

Am I missing something here?

2

Answers


  1. Chosen as BEST ANSWER

    I found out two alternatives which is working. The first one is using join but seems bit complicated (messy). The second one is subquery in orderBy

    ListingData::with($relations)
            ->orderBy(ListingPackage::select('order')->whereColumn('listing_data.listing_package_id','listing_packages.id'),'desc')
            ->latest()
                ->paginate(24);
    

    Testing performance under 50k data, took 0.027 sec

    enter image description here

    I am still searching for the most effective way to do this. Will post it here. Thank you


  2. Try this one maybe this will help you.

    $listings = ListingData::with($relations)
        ->join('listing_packages', 'listing_datas.listing_package_id', '=', 'listing_packages.id')
        ->orderByDesc('listing_packages.order')
        ->latest()
        ->paginate(24);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search