Laravel、$query、按相关表列排序时 Laravel Eloquent orderBy 出现问题

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

我在尝试按相关表中的列对查询结果进行排序时遇到了 Laravel Eloquent 的问题。具体来说,我有一个食谱表和一个相关的营养素表,我想通过营养素表中的千卡列来订购食谱。

这是我正在使用的代码片段:

$query = Recipe::with('nutrients');

// more code


if ($request->has('order_by')) {
        $orderBy = $request->input('order_by');
        $direction = $request->input('order_direction', 'asc');

        // some code
            
        elseif ($orderBy === 'kcal') {
            if ($request->has('kcal')) {
                $kcal = $request->input('kcal');
                $query->whereHas('nutrients', function ($q) use ($kcal) {
                    $q->where('kcal', '<=', $kcal);
                });
            }
            $query->orderBy('nutrients.kcal', $direction);
        }
}

// some code
return RecipesResource::collection($recipes);

型号:

Recipe:
public function nutrients()
    {
        return $this->hasOne(Nutrient::class, 'recipe_id', 'id');
    }

Nutrient:
public function recipe()
    {
        return $this->hasOne(Recipe::class);
    }

但是,此代码会导致 SQL 错误:“未找到列:1054 'order Clause' 中的未知列 '营养素.kcal'”。尝试对结果进行排序时,Laravel 似乎无法识别营养表中的 kcal 列。

我尝试了不同的方法,包括在 orderBy 子句中显式指定表名,但到目前为止,我还无法解决该问题。

任何人都可以深入了解为什么会发生此错误以及如何按 Laravel Eloquent 中相关表中的列正确排序查询结果吗?

php laravel eloquent
1个回答
0
投票

无论你的代码质量如何,在审查你的代码后,我认为问题出在这里:

 $query->whereHas('nutrients', function ($q) use ($kcal) {
                $q->where('kcal', '<=', $kcal);
            });

更改此“$q->where('kcal', '<=', $kcal);" to "$q->where('营养素.kcal', '<=', $kcal);" , I assumed that "nutrients" table does have 'kcal' column exists , Thanks if it helps.

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