如何创建一个基于数据库中现有字段而不是输入参数的where
子句?
$query = DB::table('events')
->join('events_dates', function($join) use ($data){
$join->on('events.id', '=', 'events_dates.event_id');
$join->where('events_dates.start_date', "<=", $data['date_end']);
$join->where('events_dates.end_date', '>=', $data['date_start']);
});
这很好用,因为 where 子句基于输入参数。
我需要的是一个基于数据库中已有字段的 Where 子句:
像这样:
$query = DB::table('events')
->join('events_dates', function($join) use ($data){
$join->on('events.id', '=', 'events_dates.event_id');
//If db field of record: recurrent == 0 then
$join->where('events_dates.start_date', "<=", $data['date_end']);
$join->where('events_dates.end_date', '>=', $data['date_start']);
/* If db field of record: "recurrent" == "1" then
$join->where //another query
*/
});
这可以通过 laravel ORM 实现吗,或者我应该编写一个本机 SQL 查询?
在文档或现有帖子中没有找到合适的答案。
你需要使用...
where('column1', '=', DB::raw('column2'));
。使用字段值而不是字符串"column2"。
在这个回答中,我进一步解释了原因。