在雄辩的两个不同的相关表中排序

时间:2018-05-08 16:14:07

标签: php laravel eloquent lumen

我正在努力尝试将orderBy参数传递给关系表。

这就是我的情况:我想通过书籍表上的某些列(这样做很好)以及更多书籍的订单来排序结果,但我在任何books_offers列中都会出现SQLSTATE[42S22]: Column not found: 1054 Unknown column错误。< / p>

http://localhost:8000/offers //很好

http://localhost:8000/offers?oderBy=category:asc //很好

http://localhost:8000/offers?oderBy=countries:asc //错误

   class OffersController extends Controller
    {
        public function index(Request $request)
        {
            $limit = $request->input('limit', 30);
            $offset = $request->input('offset', 0);
            $orderByInput = $request->input('orderBy');
            $orderByParams = !empty($orderByInput) ? explode(':', $orderByInput): ['id', 'DESC'];

            $offersQuery = Books::where('is_direct', '=', 1)
                ->with('offers')
                ->whereHas('offers', function ($query) {
                    $query->enable()
                    ->select(['id', 'offer_id', 'name', 'devices', 'countries', 'payment_type']); // I want to order by using this columns too
                })
                ->limit($limit)
                ->offset($offset)
                ->orderBy($orderByParams[0], $orderByParams[1]); //this works just fine with id, name and category
                $result = $offersQuery->get(['id', 'name', 'category', 'description']);

        return response()->json($OffersQuery, 200);
    }

你能给我一些建议吗?

1 个答案:

答案 0 :(得分:0)

books还是book_offers表中的countries字段?我在book_offers中考虑它,因此需要根据https://laravel.com/docs/5.6/eloquent-relationships#querying-relations来限制急切加载

使用您的特定设置(按模型上的属性或其中一个急切加载的关系模型排序)我不确定是否可以这样做。

继承人如何限制急切的负担

class OffersController extends Controller
{
    public function index(Request $request)
    {
        $limit = $request->input('limit', 30);
        $offset = $request->input('offset', 0);
        $orderByInput = $request->input('orderBy');
        $orderByParams = !empty($orderByInput) ? explode(':', $orderByInput): ['id', 'DESC'];

        $offersQuery = Books::where('is_direct', '=', 1)
            ->with('offers')
            ->whereHas('offers', function ($query) {
                $query->enable()
                ->select(['id', 'offer_id', 'name', 'devices', 'countries', 'payment_type']); // I want to order by using this columns too
                ->orderBy('id', 'desc');
            })
            ->limit($limit)
            ->offset($offset);
            $result = $offersQuery->get(['id', 'name', 'category', 'description']);

    return response()->json($OffersQuery, 200);
}