Eloquent ORM 检查 GET() 中的 IFNULL()

Dev*_*Dev 0 php eloquent laravel-4

我正在LARAVEL 4MySQL后端一起使用。我是新手。

我有一个语句从 3 个不同的表返回记录,如下所示:

$templates = Template::with('children')
                    ->leftJoin('template_masters', function($join) {
                        $join->on('templates.template_master_id', '=', 'template_masters.id');
                    })
                    ->leftJoin('surveyes', function($join) {
                        $join->on('templates.survey_id', '=', 'surveyes.id');
                    })
                    ->get([
                    'templates.id',
                    'templates.survey_id',
                    'surveyes.title', // Here I want the IFNULL() condition e.g. IFNULL('surveyes.title','templates.title')
                    'templates.type',
                    'templates.created_at',
                    'template_masters.is_default'
                    ]);
Run Code Online (Sandbox Code Playgroud)

基本上这会创建一个类似的查询:

select `templates`.`id`, 
    `templates`.`survey_id`, 
    `surveyes`.`title`, 
    `templates`.`type`, 
    `templates`.`created_at`, 
    `template_masters`.`is_default` 
from `templates` 
    left join `surveyes` on `templates`.`survey_id` = `surveyes`.`id` 
    left join `template_masters` on `templates`.`template_master_id` = `template_masters`.`id`
Run Code Online (Sandbox Code Playgroud)

但我想要这样的查询:

select `templates`.`id`, 
    `templates`.`survey_id`, 
     IFNULL(`surveyes`.`title`, `templates`.`title`),
    `templates`.`type`, 
    `templates`.`created_at`, 
    `template_masters`.`is_default` 
from `templates` 
    left join `surveyes` on `templates`.`survey_id` = `surveyes`.`id` 
    left join `template_masters` on `templates`.`template_master_id` = `template_masters`.`id`
Run Code Online (Sandbox Code Playgroud)

简而言之,而不是surveyes. title,我想要IFNULL(调查.标题,模板.标题)

->GET([])我怎样才能在给定的声明中实现这一点Eloquent ORM

谢谢。

Jar*_*zyk 5

您需要使用原始语句:

...
->get([
  'templates.id',
  'templates.survey_id',
  DB::raw('IFNULL(surveyes.title,template_masters.title) as title'),

  // or if you use namespace:
  \DB::raw('IFNULL(surveyes.title,template_masters.title) as title'),

  'templates.type',
  'templates.created_at',
  'template_masters.is_default'
]);
Run Code Online (Sandbox Code Playgroud)