【问题标题】:How to order by where in fields in Laravel如何在 Laravel 的字段中按位置排序
【发布时间】:2013-11-02 20:16:57
【问题描述】:

我在 MYSQL 中的产品视图表中做了一些计算,所以我列出了这些 id 作为产品参考 id。

$referenceIds = viewTable::orderBy('score', 'DESC')->lists('product_id');

我想从这些参考 ID 中获取产品。

$products = Product::whereIn('id', $rederenceIds);

产品内容是正确的,但是顺序不对,如何通过引用id加载产品订单,我知道我可以在MySQL中使用ORDER BY FIELD(id,' . $fields . '),但是我想了解Laravel的方式,希望不要使用ORDER BY FIELD 命令,因为它似乎浪费了很多数据库效率。

【问题讨论】:

  • 作为最终结果,您是要订购产品还是参考 ID?
  • orderBy(DB::raw('FIELD(id, ' . implode(',', $productStarScoreIds) . ')'), 'ASC'),这是解决方案,但如果可能的话,我想找出 Laravel 解决方案。

标签: mysql laravel


【解决方案1】:

不确定我是否完全理解这一点,但如果您想订购产品,您应该使用

$referenceIds = viewTable::lists('product_id');

$ordered_products = Product::whereIn('id', $rederenceIds)->orderBy('id', 'DESC')->get();

【讨论】:

  • 我想通过参考产品 ID 订购,而不是结果产品 ID。
【解决方案2】:

您将不得不注入一些原始 sql,但这不是一场噩梦:

$referenceIds = viewTable::orderBy('score', 'DESC')->lists('product_id');
$referenceIdsStr = implode(',', $referenceIds);
$products = Product::whereIn('id', $rederenceIds)->orderByRaw(DB::raw("FIELD(product_id, $referenceIdsStr)"))->get()->all();

【讨论】:

  • 如果您已经在使用orderByRaw,则无需使用DB :: raw
【解决方案3】:

如果键是主键(我认为在这个问题中它是......),你可以试试这个:

$products = Product::whereIn('id', $rederenceIds)->get();
$products = array_replace(array_flip($rederenceIds), $products->getDictionary());

结果是Array,而不是Collection

不知道是不是效率问题,但是order by field还有其他问题。例如,sqlite 不支持按字段排序,因此它不适用于使用内存数据库进行测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-29
    • 2017-12-05
    • 2020-09-05
    • 2020-07-19
    • 2019-05-06
    • 2018-07-09
    • 2021-02-07
    • 1970-01-01
    相关资源
    最近更新 更多