简体   繁体   English

将 SQL 查询转换为 eloquent

[英]Transposing SQL query to eloquent

I've been stuck on transposing this sql query to eloquent.我一直坚持将这个 sql 查询转换为 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.这些是我的模型。

Models (Many to Many)模型(多对多)

Host
- id
- apptype
- country
- ...

Vuln
- id
- severity
- ...

Host_Vuln
- id
- Host_id
- Vul_id
- Mesg
- ...

Queries查询

I have the following SQL extraction which in mysql我在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

But I'm stuck on Eloquent... This is what I have但我坚持使用 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();

where the results were returned in an collection without nesting Hosts under a Vuln.结果在集合中返回,而没有在 Vuln 下嵌套主机。 The resulting collection is a plain array where each Host is mapped to a Vuln, even when a Vuln has many Hosts.生成的集合是一个普通数组,其中每个主机都映射到一个 Vuln,即使一个 Vuln 有许多主机。 This is inefficent duplication which i want to eliminate.这是我想消除的低效重复。

The end result i want is Each Vuln can have many Hosts.我想要的最终结果是每个 Vuln 可以有许多主机。 If there is no Hosts, then do not display the Vuln.如果没有 Hosts,则不显示 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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