【问题标题】:Transposing SQL query to eloquent将 SQL 查询转换为 eloquent
【发布时间】:2018-10-23 04:17:45
【问题描述】:

我一直坚持将这个 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 可以有很多主机。如果没有 Hosts,则不要显示 Vuln。

【问题讨论】:

  • 我认为有错字问题。 vuln_host 应该是 host_vulns 试试这个 ` $vulnss = DB::table('vulns') ->join('host_vulns', 'vulns.id', '=' , 'host_vulns.finding_id') ->join('hosts', 'vuln_host.host_id', '=', 'hosts.id') ->where('hosts.country', 1) ->where('hosts. apptype', 'like', 'Mob%') ->orderBy('vulns.severity', 'DESC') ->get();`
  • 嘿,谢谢!我已经测试过了,但还是不行

标签: mysql eloquent


【解决方案1】:

我真是个笨蛋。以下是完美的(虽然我仍然没有得到它;它为什么起作用)

    $filter = function ($w) { 
        $w->where('country', 1)
          ->where('apptype', 'like', 'Mob%'); 
    };

    $findings1 = Vuln::with(['hosts' => $filter])
                    ->whereHas('hosts', $filter)
                    ->get();

【讨论】:

    猜你喜欢
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    • 2015-02-24
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多