Laravel Multiple Unions
Ich habe ein Problem beim Hinzufügen einer Abfrage mit mehreren Unions auf "einfache Weise".
Ich versuche, eine Abfrage zu erstellen, die der folgenden entspricht:
$ipsql = "";
for ($n = 1; $n < $total_networks; $n++) {
$ipsql .= "(SELECT * FROM ip WHERE network = " . $n . " AND used = 0 LIMIT 5)
UNION ALL";
}
if ($n == $total_networks) {
$ipsql .= "(SELECT * FROM ip WHERE network = " . $n . " AND used = 0 LIMIT 3) ORDER BY ip_addr";
}
Ich habe keine Option für Gewerkschaften mit Eloquent gefunden, daher habe ich versucht, den Abfrage-Generator für diesen bestimmten Abschnitt zu verwenden, aber ich stoße weiterhin auf ein Problem, während ich den Builder unionAll verwende.
Mit diesem:
$ip_list = DB::table('ips')->where('network', '=', '0')->where('used', '=', '0')->limit(5);
for($n = 1; $n < $network_count; $n++){
$ip_list = DB::table('ips')->where('network', '=', $n)->where('used', '=', '0')->limit(5)->unionAll($ip_list);
}
$ips = $ip_list->get();
Ich erhalte immer wieder einen MySQL-Syntaxfehler:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax to use near
'union all ((select * from `ips` where `network` = ? and `used` = ? limit 5) unio' at line 1
(SQL:
(select * from `ips` where `network` = 16 and `used` = 0 limit 5) union all ((select * from `ips`
where `network` = 15 and `used` = 0 limit 5) union all ((select * from `ips` where `network` = 14
and `used` = 0 limit 5) union all ((select * from `ips` where `network` = 13 and `used` = 0 limit 5)
union all ((select * from `ips` where `network` = 12 and `used` = 0 limit 5) union all ((select *
from `ips` where `network` = 11 and `used` = 0 limit 5) union all ((select * from `ips` where
`network` = 10 and `used` = 0 limit 5) union all ((select * from `ips` where `network` = 9 and
`used` = 0 limit 5) union all ((select * from `ips` where `network` = 8 and `used` = 0 limit 5)
union all ((select * from `ips` where `network` = 7 and `used` = 0 limit 5) union all ((select * from
`ips` where `network` = 6 and `used` = 0 limit 5) union all ((select * from `ips` where `network` =
5 and `used` = 0 limit 5) union all ((select * from `ips` where `network` = 4 and `used` = 0 limit
5) union all ((select * from `ips` where `network` = 3 and `used` = 0 limit 5) union all ((select *
from `ips` where `network` = 2 and `used` = 0 limit 5) union all ((select * from `ips` where
`network` = 1 and `used` = 0 limit 5) union all (select * from `ips` where `network` = 0 and `used`
= 0 limit 5)))))))))))))))))
Ich kann anhand des Fehlers erkennen, dass jeder neue Union-Aufruf, der das Syntaxproblem verursacht, verschachtelt wird. Ich habe versucht, die gleiche Aufgabe mit DB :: raw zu erfüllen, aber es scheint, als ob ich das auch irgendwo vermassele. Gibt es eine Möglichkeit, dies zu erreichen, die besser für Laravel geeignet ist? Danke fürs schauen!