如何使用Laravel Eloquent编写带有”with”的查询。

huangapple go评论75阅读模式
英文:

how to write query with "with" using laravel eloquent

问题

如何在Laravel中创建一个类似下面示例的带有"with"的查询
谢谢

with s as (select s.id from s)
select a.*
from a
left join s on s.id = a.s_id
...
英文:

How to make with laravel a query with with like the example below
Thank you

with s as (select s.id from s)
select a.*
from a
left join s on s.id = a.s_id
...

答案1

得分: 0

WITH 子句不受 Eloquent 支持。您可以选择传入原始查询

$sql = <<<SQL
with s as (select s.id from s)
select a.*
from a
left join s on s.id = a.s_id
...
SQL;

$results = DB::select($sql);

或者使用像 staudenmeir/laravel-cte 这样的包来添加此功能

DB::query()
    ->withExpression('s', fn ($query) => $query->select('s.id')->from('s'))
    ->select('a.*')
    ->from('a')
    ->leftJoin('s', 's.id', 'a.s_id')
    ...
英文:

WITH clauses are not supported by Eloquent. You can either pass in a raw query

$sql = &lt;&lt;&lt;SQL
with s as (select s.id from s)
select a.*
from a
left join s on s.id = a.s_id
...
SQL;

$results = DB::select($sql);

Or use a package that adds this functionality like staudenmeir/laravel-cte

DB::query()
    -&gt;withExpression(&#39;s&#39;, fn ($query) =&gt; $query-&gt;select(&#39;s.id&#39;)-&gt;from(&#39;s&#39;))
    -&gt;select(&#39;a.*&#39;)
    -&gt;from(&#39;a&#39;)
    -&gt;leftJoin(&#39;s&#39;, &#39;s.id&#39;, &#39;a.s_id&#39;)
    ...

huangapple
  • 本文由 发表于 2023年1月8日 23:55:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75049204.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定