【问题标题】:how to select from subquery using query builder in laravel 5如何使用 laravel 5 中的查询生成器从子查询中进行选择
【发布时间】:2017-11-20 09:00:57
【问题描述】:

请帮助我, 我有疑问: SELECT * from (select * from products ORDER BY id DESC LIMIT 20) AS result ORDER BY discount DESC LIMIT 14

那么,如何在 laravel 5 中转换为查询生成器。 tks!

【问题讨论】:

  • 看看this,可能会有所帮助。
  • tks 伙计,我做到了

标签: php laravel select


【解决方案1】:

使用查询构建器和导入(使用)数据库,允许您构建和获取您想要的结果。

use DB;

$result = DB::table(
    DB::raw("(" . 
        DB::table('products')
          ->select('*')
          ->orderBy('id', 'desc')
          ->limit(20)
          ->toSql()
        . ") as result"
    )
)
->select('*')
->orderBy('discount', 'desc')
->limit(14)
->get();

table() 选择要查询的表。在这种情况下,我们正在构建一个单独的 SQL 语句来获取表。

select() 你想看的列。

orderBy($column, $direction) 其中 $column 是您要排序的列的名称,$direction 是 order、desc 或 asc。

limit($limit) 只返回 $limit 个项目到结果集。

toSql() 以字符串形式返回当前的 QueryBuilder SQL 语句。

get() 返回 Collection 中的数据。

在缺少的折扣订单中也添加了。

【讨论】:

  • 请在您的答案中添加一些上下文。仅靠代码通常不能得到好的答案
  • 我想你错过了“ORDER BY discount DESC”
【解决方案2】:

尝试类似:

Products::orderBy('id', 'desc')->take(20)->orderBy('discount', 'desc')->take(14)->get();

【讨论】:

  • tks 伙计,我试过了,但结果不是 orderBy('discount')。它给出了 14 条记录 orderby('id', 'desc')。你还有其他的制作吗?
  • 你可以使用:$q = Products::orderBy('id', 'desc')->take(20)->get();然后 $test = $q->sortByDesc('nome')->take(14);看看这是否有效
猜你喜欢
  • 2021-04-27
  • 1970-01-01
  • 2013-05-30
  • 2015-12-21
  • 2017-03-29
  • 2018-02-16
  • 2019-04-25
  • 2018-06-23
相关资源
最近更新 更多