【问题标题】:how to write query with where having multiple condition in laravel 5如何在laravel 5中编写具有多个条件的查询
【发布时间】:2016-06-02 14:34:04
【问题描述】:

我正在尝试更新表格。

我在 foreach 中拥有所有值。唯一 id 是 'uuid'

但我想更新值是否仅已更改。我试过这样做,但没有运气。

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

以下查询的 laravel 方式是什么。

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

【问题讨论】:

    标签: sql laravel-5.2 multiple-conditions


    【解决方案1】:

    试试这个。 在https://laravel.com/docs/5.2/queries#updates 中查找更多信息。

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

    在你的特殊情况下,你应该使用这个:

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

    最后一个会产生这样的结果:

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

    【讨论】:

    • 谢谢@Ignacio Fassini,这正是我想要的
    猜你喜欢
    • 1970-01-01
    • 2021-12-02
    • 2021-12-06
    • 2021-11-23
    • 2016-09-20
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    • 2018-08-14
    相关资源
    最近更新 更多