koe's avatar
Level 1

SEARCH AND ORDER IN RELATED MODELS

Hello, i make API to show Guests with pagination. There is two tables guests and cards

guests have name, surname, email, phone and cards have numbers, balance discount and bonus

sorting by guests fields work, but i have no idea how to sort it by cards number or balance

And guest usualy have one card, but can have more than one.

    public function index(Request $request)
    {
        $guests = $request->application()->guests()->with(['cards'])->where('disabled', 0);

        if ($keyword = Input::get('q')) {
            $guests->where(function ($guests) use ($keyword) {
                $guests->whereHas('cards', function ($query) use ($keyword){
                    $query->where('number', "LIKE", "%$keyword%");
                })
                    ->orWhere("name", "LIKE","%$keyword%")
                    ->orWhere("surname", "LIKE", "%$keyword%")
                    ->orWhere("email", "LIKE", "%$keyword%")
                    ->orWhere("phone", "LIKE", "%$keyword%");
            });
        }

        $order = Input::get('o', 'id');
        $destination = Input::get('d', 'DESC');

        $guests = $guests->orderBy($order, $destination);
        
        return response()->json($guests->paginate(20));
    }
0 likes
3 replies
mdeorue's avatar

You want to order by an One To Many relation the whole Collection, or you want to order the cards for any guest?

Regards

koe's avatar
Level 1

I want to order Collection. Collection must relate application (appId key), there is 60 000 items in guests and cards so it can be slow (~5k guests per application)

this is how my front table looks: id, name, cards[0].number, cards[0].balance, cards[0].bonus, email, phone, birthday, created_at

Actualy cards balances, bonuses, discounts on all cards the same, and few users have more than one cards with different numbers)

Please or to participate in this conversation.