╔═══╦══════════════╦═════════════╗
║ ║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)
如何使查询动态化,使其能够根据用户输入自动调整。
答案 0 :(得分:0)
所以,这是一个伪代码,不是laravel特有的,但希望它可以使您了解我的意思。
每个输入都作为单独的POST输入
$input1 = $_POST[input1]
$input2 = $_POST[input2]
$input3 = $_POST[input3]
用于构建查询的三个变量
$fullQuery = '';
$topQuery = '';
$bottomQuery = '';
IF (isset($input1) AND !empty($input1) AND isset($input2) AND !empty($input2))
{
$topQuery = "select t1.id as t1_id, t1.name as t1_name,
t2.id as t2_id, t2.name as t2_name";
$bottomquery = " from (select * from your_table where name like '$input1%') as t1
cross join (select * from your_table where name like '$input2%') as t2";
}
IF (isset($input1) AND !empty($input1) AND isset($input2) AND !empty($input2) AND isset($input3) AND !empty($input3))
{
$topQuery.= " ,t3.name AS t3_name"
$bottomQuery.= " CROSS JOIN (SELECT * FROM your_table WHERE NAME LIKE '$input3%') AS t3"
}
$fullQuery = $topQuery . $bottomQuery . ";";