【发布时间】:2018-05-08 16:14:06
【问题描述】:
伙计们
我在尝试将 orderBy 参数传递给关系表时遇到了困难。
这是我的情况:我想通过 books 表上的某些列(这工作得很好)以及更多的 books_offers 对结果进行排序,但我在任何 books_offers 列上都收到 SQLSTATE[42S22]: Column not found: 1054 Unknown column 错误。
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);
}
你能给我一些建议吗?
【问题讨论】:
-
这个场景你必须使用join
-
一本书可以有很多优惠,对吧?应该使用哪个报价来排序图书?
-
是的@JonasStaudenmeir,一本书可以有很多优惠。我应该按设备、offer_id、payment_type 和国家对结果进行排序。
-
如果一本书有三个具有不同
countries值的报价,查询应该使用哪一个来对这本书进行排序? -
嗨 @JonasStaudenmeir 没关系,应该按国家值 asc 或 dsc 订购所有报价。
标签: php laravel eloquent lumen