【问题标题】:Laravel: where condition based on db fieldLaravel:基于数据库字段的条件
【发布时间】:2015-02-26 20:40:15
【问题描述】:

如何根据数据库中的现有字段而不是输入参数创建whereclause?

$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 查询?
在文档或现有帖子中没有找到合适的答案。

【问题讨论】:

    标签: php mysql laravel laravel-4 orm


    【解决方案1】:

    你需要使用...

    where('column1', '=', DB::raw('column2'));
    

    ...使用字段值代替字符串“column2”。

    this answer我进一步解释了原因。

    【讨论】:

    • 好的,我应该在 join 子句中使用嵌套的 where 来满足问题中提出的要求吗?我会做一些测试看看效果如何。
    • 这基本上是您发布here 的问题,对吧?如果我找到解决方案,我会看看它并在那里回答。这里有点离题(考虑到问题标题)
    • 是的,它指的是同一个问题,但我认为上一个问题可能不够简单。感谢您的努力,我今天已经搜索了几个小时,但到目前为止一直无法正确找到它。
    • 您会考虑接受这个答案吗?你必须承认,它回答了这个问题(即使它对你没有多大帮助;))
    猜你喜欢
    • 2019-12-30
    • 2019-09-29
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多