Cristian Salinas
Cristian Salinas

Reputation: 25

How to make this type of query in Laravel?

This is the sql query but how can I do it in 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())

This is the code that I tried to make:

$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'));

Upvotes: 0

Views: 108

Answers (2)

Harun
Harun

Reputation: 1237

You can simply do that without thinking about the complexity of converting or splitting queries to multiple query builder statements.

$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);

Upvotes: 0

nikistag
nikistag

Reputation: 694

There are two queries anyway so..

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

then,

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

Upvotes: 1

Related Questions