[英]Transposing SQL query to eloquent
我一直堅持將這個 sql 查詢轉換為 eloquent。 我已經嘗試了很多,但雄辯的結果並沒有以我想要的格式返回,即:
Vuln A
- Host 1
- Host 2
Vul B
- Host 3
Vul C
- Host 1
- Host 2
- Host 5
這些是我的模型。
Host
- id
- apptype
- country
- ...
Vuln
- id
- severity
- ...
Host_Vuln
- id
- Host_id
- Vul_id
- Mesg
- ...
我在mysql中有以下SQL提取
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
但我堅持使用 Eloquent ......這就是我所擁有的
$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();
結果在集合中返回,而沒有在 Vuln 下嵌套主機。 生成的集合是一個普通數組,其中每個主機都映射到一個 Vuln,即使一個 Vuln 有許多主機。 這是我想消除的低效重復。
我想要的最終結果是每個 Vuln 可以有許多主機。 如果沒有 Hosts,則不顯示 Vuln。
我真是個笨蛋。 以下是完美的(雖然我仍然沒有得到它;為什么它有效)
$filter = function ($w) {
$w->where('country', 1)
->where('apptype', 'like', 'Mob%');
};
$findings1 = Vuln::with(['hosts' => $filter])
->whereHas('hosts', $filter)
->get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.