dimanche 5 août 2018

Laravel - how to surround all previous clauses with where clause on builder ?

In database table I have one row :

users
id|email|is_deleted
1|test@test.com|1

I have this code :

User::where('email', 'test@test.com')
    ->orWhere('email', 'test2@test2.com')
    ->get();

and this query is generated :

select * from users where email = 'admin@myzone.com' or email = 'asdasdas'

with one result. Now I want apply where is_deleted = 0

If I do like this :

User::where('email', 'test@test.com')
    ->orWhere('email', 'test2@test2.com')
    ->where('is_deleted', 0)
    ->get();

Generated query is :

select * from "users" where "email" = ? or "email" = ? and "users"."deleted_at" is null

So far everything works as expected, this query returns one result, but I want only not deleted users, I can do following :

User::where(function($query){
    $query->where('email', 'test@test.com')
        ->orWhere('email', 'test2@test2.com')
})->where('is_deleted', 0)
->get();

and this will work, but in my code I already have returned builder :

function applyNotDeleted(Builder $builder){
    //here I want to filter only not deleted users, 
    //but this is already triggered on builder $query->where('email', 'test@test.com')->orWhere('email', 'test2@test2.com')

    //currently generated query on builder is select * from users where email = 'admin@myzone.com' or email = 'asdasdas'
    //but at this stage I want to create query which will look like select * from "users" where "email" = ? or "email" = ? and "users"."deleted_at" is null

    //something like this 
    $builderNew = $builderNew->where(function($query){
        $query->applyAllLogicFromCurrentBuilder($builder)
    })
    ->where('is_deleted', 0)
    ->get();
}

any idea?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire