简体   繁体   中英

How to make query from related models in Laravel?

I happen to have: Sale model that has: id, product_id, qty, s_price ; Product model that has: id, category_id, name ; Category model that has: id, name

Currently l can make this query successfully:

 $sales = Sale::orderBy('created_at', 'DESC')
                ->whereBetween('created_at', [$startDate, $endDate])
                ->whereBetween('qty', [$lQty, $uQty])
                ->paginate(11);

I know the category_id and want to filter out only sales of products that belong a particular category. Something like:

 $sales = Sale::orderBy('created_at', 'DESC')
                    ->whereBetween('created_at', [$startDate, $endDate])
                    ->whereBetween('qty', [$lQty, $uQty])
                    ->where('category_id', '=', 5)
                    ->paginate(11);

You can try this

$sales = Sale::whereHas('product', function ($query) {
                $query->where('category_id', '=', 5);
            })
            ->whereBetween('created_at', [$startDate, $endDate])
            ->whereBetween('qty', [$lQty, $uQty])
            ->orderBy('created_at', 'DESC')
            ->paginate(11);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM