繁体   English   中英

将 SQL 查询转换为 eloquent

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM