How to do common table expressions in laravel / eloquent for mysql 8?

懵懂的女人 提交于 2019-12-11 05:58:40

问题


what is the proper way of doing CTE common table expressions in laravel 5.7?

consider this sql:

WITH
SearchTerm AS (
  SELECT
    ROW_NUMBER() OVER (ORDER BY created_at) AS search_term_order
    , jobs.*
  FROM jobs
  WHERE description LIKE '%programmer%'
),
PremiumAdd AS (
  SELECT
    ROW_NUMBER() OVER (ORDER BY created_at DESC) AS premium_order
    , jobs.*
  FROM jobs
  WHERE is_premium = 1
),
FinalOrder AS (
  SELECT
    id
    , description
    , created_at
    , is_premium
    , MOD(search_term_order + 1, 2) + FLOOR((search_term_order + 1) / 2) * 3 - 2 AS position
  --  , MOD(search_term_order + 2, 3) + FLOOR((search_term_order + 2) / 3) * 4 - 3 AS position
  FROM SearchTerm
  UNION ALL
  SELECT
    id
    , description
    , created_at
    , is_premium
    , premium_order * 3
  --  , premium_order * 4
  FROM PremiumAdd
  ORDER BY position
)
SELECT
  id, description, created_at, is_premium FROM FinalOrder
;

回答1:


Laravel has no CTE support. You can use a raw query and hydrate the models yourself:

$rows = DB::select($sql, $bindings);

$jobs = Job::hydrate($rows);

I've created a package for common table expressions: https://github.com/staudenmeir/laravel-cte

class Job extends Model
{
    // Required in Laravel 5.5–5.7:
    // use \Staudenmeir\LaravelCte\Eloquent\QueriesExpressions;
}   

$jobs = Job::from('FinalOrder')
    ->withExpression('SearchTerm', 'SELECT ROW_NUMBER() [...]')
    ->withExpression('PremiumAdd', 'SELECT ROW_NUMBER() [...]')
    ->withExpression('FinalOrder', 'SELECT id, description [...]')
    ->select('id', 'description', 'created_at', 'is_premium')
    ->get();


来源:https://stackoverflow.com/questions/54194241/how-to-do-common-table-expressions-in-laravel-eloquent-for-mysql-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!