Laravel mysql 多个where查询

Laravel mysql multiple where query

我有以下

return DB::table('recipe_symbols')
   ->where('symbol_id', 8)
   ->get(['recipe_id']);

它工作得很好。现在我有以下 return 更过滤的结果

return DB::table('recipe_symbols')
   ->where('symbol_id', 8)
   ->where('symbol_id', 16)
   ->get(['recipe_id']);

我没有得到任何结果,即使 symbol_id 8 和 16 的行存在。我尝试了原始查询,但仍然是同样的问题。

出了什么问题?我想要实现的是根据用户选择的符号 symbol_id 获取食谱。

我尝试了 whereIn(),但这带回了具有特定 symbol_id 但没有其他的食谱。例如,它带来了 2 个食谱,其中一个的 symbol_id 只有 8,第二个有 8 和 16。我需要得到所有 symbol_id = 8 和 16 的食谱,没有别的。

编辑*** 数据库结构

recipe_symbols_table
----------------------
|id | recipe_id | symbol_id |
-----------------------------
|1  | 2         | 8
|2  | 2         | 16
|3  | 3         | 8
|4  | 3         | 16
|5  | 4         | 8
|6  | 4         | 30
|7  | 5         | 8
|8  | 5         | 28    
|9  | 6         | 8
|10 | 6         | 31
|11 | 7         | 8
|12 | 7         | 18

编辑***

$sql = 'SELECT * FROM sie_hp_cookbook_recipes_symbols WHERE symbol_id=8 and symbol_id=16';
$qry = DB::select($sql);

原始查询

SELECT a.recipe_id FROM (
  (select * from recype_symbols where symbol_id = 8) a 
  join (select * from recype_symbols where symbol_id = 16) b 
  on 
  a.recipe_id = b.recipe_id)

我不确定laravel方式是否正确

 DB::table('recype_symbols')
            ->join(DB::raw('(select *  from recype_symbols where symbol_id = 16 or symbol_id = 8) as b'),'recype_symbols.recipe_id','=','b.recipe_id')
                ->where('recype_symbols.symbol_id',8)
                ->where('b.symbol_id',16)
                ->select(['recype_symbols.recipe_id'])
                ->get();

如果我理解正确的话,您需要所有 recipe_id 存在某些符号的地方。


这在MySQL

中很难

这在 MySQL 中不会是微不足道的。因为 MySQL 逐行解析只是做一个 AND 将 return 什么都没有。一行不能有 8 和 16 的 symbol_id

因此我们需要比较具有相同行的两个表。这通常通过 JOIN 和相交来完成。但是 MySQL 不支持相交。 (因此出现问题。)


如何解决

结合使用 UNIONGROUP BY 我们可以模拟交叉路口,但我不知道如何使用 Eloquent。

因此,您最好的选择是 raw_query。对此的原始 MySQL 查询将是

SELECT recipe_id from (
 (SELECT * FROM sie_hp_cookbook_recipes_symbols WHERE symbol_id=8)
 UNION ALL 
(SELECT * FROM sie_hp_cookbook_recipes_symbols WHERE symbol_id=16)
) AS t1 GROUP BY recipe_id HAVING count(*) >= 2;

Link 举个例子fiddle http://sqlfiddle.com/#!9/c4150/15/0


现在 Laravel 解决方案

$first= DB::table('recipe_symbols')
                           ->where('symbol_id', 8);
return DB::table('recipe_symbols')->where('symbol_id', 16)
                           ->unionAll($first)
                           ->groupBy('recipe_id')
                           ->having('count(*)>2')
                           ->select(['recipe_id'])
                           ->get();

复杂,嗯!

下面给出了前两个结果(2 和 3)。希望这对您有所帮助!

SELECT a.`recipe_id`
FROM `recipe_symbols_table` a
    INNER JOIN `recipe_symbols_table` b
        ON a.`recipe_id` = b.`recipe_id`
WHERE b.`symbol_id` IN (8,16)
GROUP BY a.`recipe_id`
HAVING COUNT(DISTINCT b.`symbol_id`) = 2