如何在Laravel中进行此类查询?

时间:2019-10-30 08:38:59

标签: sql laravel

这是sql查询,但是如何在laravel中完成呢?

SELECT id FROM clientes where email is null and phone is null and id in(SELECT DISTINCT(cliente_id) FROM reservas WHERE dia < now())

这是我尝试制作的代码:

$usersIdDel = DB::table("clientes")->select('id')
            ->whereNotNull('email')->whereNotNull('phone')
            ->whereIn('id',function($query){            $query->select('cliente_id')->from('reservas')->distinct()->where('dia','<',date('Y-m-d'));
            })
            ->get();
      $clientes = Cliente::select()->orderBy('nombre', 'desc')->get();
        return view('admin.clientes.index')->with(compact('clientes'));

2 个答案:

答案 0 :(得分:1)

反正有两个查询。

 $clientIds =  DB::table('reservas')->select('cliente_id')->distinct()->where('dia','<',date('Y-m-d'))->get();

然后

$usersIdDel = DB::table("clientes")->select('id')
        ->whereNotNull('email')->whereNotNull('phone')
        ->whereIn('id', $clientIds->pluck('cliente_id')->all())
        ->get();

答案 1 :(得分:0)

您可以简单地这样做,而无需考虑将查询转换或拆分为多个查询构建器语句的复杂性。

$sql = "SELECT id FROM clientes where email is null and phone is null and id in(SELECT DISTINCT(cliente_id) FROM reservas WHERE dia < now())";
$result = DB::select($sql);