Laravel查询构建器中的Multiple Where子句

时间:2019-06-07 18:15:59

标签: php mysql laravel

我正在尝试在Laravel查询构建器中编写MySql查询,但是它返回表中的所有数据。 where子句很可能无法正常工作。另外,当我将这一行->orWhereNull([$request->name])放入时,它会显示错误。由于我是Laravel查询构建器的新手,请帮助我离开这里。

MySql查询:

SELECT t.trans_date, c.cust_id, c.first_name, c.name_name, t.notes_by, t.behavioural_notes
FROM time_trans t
JOIN customers c ON t.cust_id=c.cust_id
WHERE (t.trans_date BETWEEN 'param_date' AND 'param_date')AND (c.cust_id = '10034' OR param = NULL) AND t.behavioural_notes IS NOT NULL

查询构建器:

$data=DB::table('time_trans as t')
            ->join('customers as c','c.cust_id','=','t.cust_id')
            ->select('t.trans_date', 'c.cust_id', 'c.first_name', 'c.name_name', 't.notes_by', 't.behavioural_notes')
            ->WhereBetween('t.trans_date', [$request->from_date, $request->to_date])
            ->WhereNotNull('t.behavioural_notes')
            ->Where('c.cust_id','=',[$request->name])
            ->orWhereNull([$request->name])
            ->get();

1 个答案:

答案 0 :(得分:0)

你能检查一下吗?

$data=DB::table('time_trans as t')
         ->join('customers as c','c.cust_id','=','t.cust_id')
        ->select('t.trans_date', 'c.cust_id', 'c.first_name', 'c.name_name', 't.notes_by', 't.behavioural_notes')
        ->where(function ($query) use ($request) {
                $query->WhereBetween('t.trans_date', [$request->from_date, $request->to_date])
                        ->WhereNotNull('t.behavioural_notes')
                         ->Where('c.cust_id','=',[$request->name]);
            })
        ->orWhereNull([$request->name])
        ->get();

也不需要在orWhereNull([$ request-> name])中传递数组。它接受单个字符串列名称。

已编辑:- 看着Mysql查询修改了

$data=DB::table('time_trans as t')
                        ->join('customers as c','c.cust_id','=','t.cust_id')
                        ->select('t.trans_date', 'c.cust_id', 'c.first_name', 'c.name_name', 't.notes_by', 't.behavioural_notes')
                        ->WhereBetween('t.trans_date', [$request->from_date, $request->to_date])
                        ->where(function ($query) use ($request) {
                            $query->Where('c.cust_id','=',[$request->name])
                                ->orWhereNull(c.cust_id)
                        })
                        ->WhereNotNull('t.behavioural_notes')
                        ->get();

为什么要向orWhereNull传递$ request-> param,它应该是col名称。可能是经过编辑的Querybuilder可以为您提供帮助。您可以根据需要在orWhereNull中更新列名称。