将我的sql查询转换为laravel查询

时间:2017-07-27 10:36:45

标签: mysql laravel

我想将普通的sql转换为laravel查询.Property是模型名称。 ..请告诉我这个查询laravel模型查询

SELECT * FROM property WHERE
property.active = 1 AND 
on_market = 1 AND
department = 'lettings' AND
price > 0 AND
( submitted_at IS NULL OR submitted_at = '0000-00-00 00:00:00' OR ( submitted_at IS NOT NULL AND approved_at IS NOT NULL ) )enter code here

4 个答案:

答案 0 :(得分:0)

尝试以下查询:

Property::where('active',1)
    ->where('on_market',1)
    ->where('department','lettings')
    ->where('price','>',0)
    ->where(function ($query) {
               $query->isNull('submitted_at')
              ->orWhere('submitted_at','0000-00-00 00:00:00')
              ->orWhere(function ($query2) {
                  $query2->whereNotNull('submited_at')->whereNotNull('approved_at')
            })
})->get();

答案 1 :(得分:0)

use property;
use DB;
DB::table('property')
->where('on_market ', '=', 1)
->where('active', '=', 1)
->where('department', 'lettings')
->where('price', '=', 0)
->orWhereNotNull('submitted_at')
->or_where('submitted_at' '=','0000-00-00 00:00:00')
->orWhereNotNull('submitted_at')
   ->whereNotNull('approved_at')

答案 2 :(得分:0)

尝试此查询,该查询使用原始WHERE:

DB::table('property')
        ->select('*')
        ->where('active', '=', 1)
        ->where('on_market', '=', 1)
        ->where('department', '=', 'lettings')
        ->where('price', '>', 0)
        ->where(DB::raw("COALESCE(submitted_at, '0000-00-00 00:00:00') = '0000-00-00 00:00:00' OR approved_at IS NOT NULL"))
        ->get();

我认为最终OR条件中WHERE的后半部分可以缩短为approved_at IS NOT NULL,因为submitted_at已经不是NULL了要考虑这个条件。

此外,如果您真的希望submitted_at的值为0000-00-00 00:00:00,则会产生代码异味。理想情况下,您只需检查NULL,但无论如何我对COALESCE()的使用应符合您的预期逻辑。

答案 3 :(得分:0)

试试这可能会对你有所帮助

$sql_query =  DB::table('property AS p')
                        ->select('*')
                        ->where('p.active','=',1)
                        ->where('on_market','=','lettings')
                        ->where('price','>',0)
                        ->where(DB::raw("COALESCE(submitted_at, '0000-00-00 00:00:00') = '0000-00-00 00:00:00' OR approved_at IS NOT NULL"))
                        ->get();

    $sql_query = json_decode(json_encode($sql_query), true);

在变量$sql_query中,您将获得结果数组