I've been stuck on transposing this sql query to eloquent. I've tried quite a fair bit but the eloquent results were not returning in the format i want, namely:
Vuln A
- Host 1
- Host 2
Vul B
- Host 3
Vul C
- Host 1
- Host 2
- Host 5
These are my models.
Host
- id
- apptype
- country
- ...
Vuln
- id
- severity
- ...
Host_Vuln
- id
- Host_id
- Vul_id
- Mesg
- ...
I have the following SQL extraction which in mysql
SELECT * from Vuln
INNER JOIN Host_Vuln on Host_Vuln.Vuln_id = Vuln.id
INNER JOIN Host on Host_Vuln.Host_id = Host.id
WHERE (Host.country = 1) AND (Host.apptype like 'Mob%')
ORDER BY Vuln.severity DESC
But I'm stuck on Eloquent... This is what I have
$vulnResult = DB::table('vulns')
->join('host_vuln', 'vulns.id', '=', 'host_vuln.finding_id')
->join('hosts', 'host_vuln.host_id', '=', 'hosts.id')
->where('hosts.country', 1)
->where('hosts.apptype', 'like', 'Web%')
->orderBy('vulns.score', 'DESC')
->get();
where the results were returned in an collection without nesting Hosts under a Vuln. The resulting collection is a plain array where each Host is mapped to a Vuln, even when a Vuln has many Hosts. This is inefficent duplication which i want to eliminate.
The end result i want is Each Vuln can have many Hosts. If there is no Hosts, then do not display the Vuln.
I was such a dumbarse. The following was perfect (though I still didn't get it; why it worked )
$filter = function ($w) {
$w->where('country', 1)
->where('apptype', 'like', 'Mob%');
};
$findings1 = Vuln::with(['hosts' => $filter])
->whereHas('hosts', $filter)
->get();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.