【发布时间】:2018-12-07 00:15:52
【问题描述】:
╔═══╦══════════════╦═════════════╗
║ ║id ║name ║
╠═══╬══════════════╬═════════════╣
║ ║ 1 ║a1 ║
║ ║ 2 ║b1 ║
║ ║ 3 ║b2 ║
║ ║ 4 ║c1 ║
║ ║ 5 ║c2 ║
╚═══╩══════════════╩═════════════╝
我正在使用 laravel 和 mysql
考虑这张表。
我想生成输入用户指定的所有组合。例如,如果用户输入 (a,b) 我的代码应该生成 (a1,b1) , (a1,b2)
如果用户输入(b,c) 我的代码应该生成(b1,c1), (b1,c2), (b2,c1), (b2,c2)
到目前为止,我有以下查询:
DB::select(DB::raw("select t1.id as t1_id, t1.name as t1_name,
t2.id as t2_id, t2.name as t2_name,
t3.id as t3_id, t3.name as t3_name,
from (select * from table where name like 'a%') as t1
cross join (select * from table where name like 'b%') as t2
cross join (select * from table where name like 'c%') as t3"));
但是,此查询仅限于我知道用户输入的情况,例如在这种情况下,用户输入 3 个变量,即(a,b,c)
如何使查询动态化,以便它根据用户输入自动调整。
【问题讨论】:
-
您应该使用基于用户输入的 foreach 循环在 php 中动态构建查询。在我的手机上,或者我会分享更多。只是评论,因为没有其他人回答。
-
@Bleach 你的意思是像在循环中将查询构建为字符串然后运行该查询,对吧?
-
这正是我的意思
-
@Bleach 如果你能写一个答案,那就太好了!