Упорядочить в двух разных связанных таблицах на eloquent - PullRequest
0 голосов
/ 08 мая 2018

1001 * ребята *

Я пытался передать аргумент orderBy в реляционные таблицы.

Это мой случай: я хочу упорядочить результат по некоторым столбцам в таблице книг (это работает просто отлично), а также по некоторым другим books_offers, но я получаю ошибку SQLSTATE[42S22]: Column not found: 1054 Unknown column с любым столбцом books_offers.

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 голосов
/ 09 мая 2018

Поле стран указано в таблице books или book_offers? Я думаю, что это в 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);
}
...