OrderBy Laravel 雄辩关系

问题描述 投票:0回答:1

我想根据listing_packages.order订购listing_data。这是查询

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

我想根据listing_package.order“DESCENDING”进行订购

然而,它又回来了

SQLSTATE[42S22]:未找到列:1054 未知列 “order 子句”中的“listing_package.order”

这是模型ListingData.php

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

这是 ListingPackage.php 的模型

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

编辑:

我也试试这个

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

但是数据没有排序

我在这里遗漏了什么吗?

php laravel
1个回答
0
投票

我发现了两种有效的替代方案。第一个是使用 join 但看起来有点复杂(混乱)。第二个是 orderBy 中的子查询

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

测试50k数据下的性能,耗时0.027秒

我仍在寻找最有效的方法来做到这一点。将在这里发布。谢谢你

© www.soinside.com 2019 - 2024. All rights reserved.