问题
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