【问题标题】:Convert Mysql query to Laravel将 Mysql 查询转换为 Laravel
【发布时间】:2018-08-10 22:24:03
【问题描述】:

我想将 mysql 查询转换为 laravel 查询。

MySQL:

select product_id as urun from product_features 
   where feature_id = 58 
      or feature_id = 100 
      or (feature_id = 52 or feature_id = 48 or feature_id = 53)      
   group by product_id having(count(product_id)>2)

编辑:我不能将“或”表达式括在括号中。

【问题讨论】:

  • 您的模型和关系设置是否正确?
  • 谢谢。但我不能将“或”表达式括在括号中。
  • idownvotedbecau.se/noattempt 。此外,当您单击创建此帖子时,按钮显示“”。从什么时候开始“我想要”成为一个问题或问题?我们将帮助您修复错误,而不仅仅是完全为您完成工作。你做了什么研究?你试过什么代码?你面临什么问题?请阅读stackoverflow.com/help/how-to-ask 以获取有关如何提出有用问题的进一步指导。
  • 这是一个简单的帖子,没有以最好的方式表达,当然应该进行编辑,但见鬼,没有理由淘汰新用户。

标签: mysql laravel


【解决方案1】:

编辑:我不能将“或”表达式括在括号中。

当然可以。 :-)

你想看看 Laravel 的 parameter grouping 功能。

$query->orWhere(function($query) {
    $query->where('foo', 'bar')
          ->orWhere('foo', 'not-bar');
});

【讨论】:

    【解决方案2】:

    我解决了这个问题。

    $query = DB::table('product_features')->where('feature_id', 52)->orWhere('feature_id', 48)->orWhere('feature_id', 53)->
        orWhere('feature_id', 100)->orWhere('feature_id', 58)->
        select('product_id')->groupBy('product_id')->havingRaw("count(product_id) > 2")->get();
    

    【讨论】:

    • 虽然这适用于您的特定情况,但这不会产生括号,这会导致更复杂的查询出现问题。请参阅我的回答,了解如何处理查询的括号部分。
    • 我会照你说的做。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-07
    相关资源
    最近更新 更多