sanainfotech
sanainfotech

Reputation: 691

how to write query with where having multiple condition in laravel 5

I am trying to update the table.

I have all values in foreach. The unique id is 'uuid'

But I would like to update if the value has been changed only. I tried to do this but no luck.

$results = DB::table('urls')
                    ->where('uuid','=',$uuid)
                    ->orWhere('id_media', '!=',$id_media)
                    ->orWhere('region', '!=',$region)
                    ->orWhere('page', '!=',$page)
                    ->orWhere('audience', '!=',$audience)
                    ->update(array(
                        'id_media' => $id_media,
                        'region'=>$region,
                        'page'=>$page,
                        'audience'=>$audience
                    ));

what would be the laravel way for below query.

update my_table set
my_col = 'newValue'
where id = 'someKey'
and my_col != 'newValue';

Upvotes: 0

Views: 667

Answers (1)

Ignacio Fassini
Ignacio Fassini

Reputation: 66

try this. find more in https://laravel.com/docs/5.2/queries#updates.

DB::table('my_table')
    ->where('id', 1)
    ->where('my_col', '!=', 'newValue')
    ->update(['my_col' => 'newValue']);

In your particular case, you should use this:

DB::table('urls')
        ->where('uuid', '=', $uuid)
        ->where(function ($query) use ($id_media, $region, $page, $audience) {
            $query->orWhere('id_media', '!=', $id_media)
                ->orWhere('region', '!=', $region)
                ->orWhere('page', '!=', $page)
                ->orWhere('audience', '!=', $audience);
        })
        ->update([
            'id_media' => $id_media,
            'region' => $region,
            'page' => $page,
            'audience' => $audience
        ]);

The last would produce something like this:

update my_table set
    my_col = 'newValue'
where id = 'someId' and 
    (my_col1 != 'newValue1' or my_col2 != 'newValue2' or .. );

Upvotes: 1

Related Questions