Laravel 数据库:合并多个 where 请求 2 个改进

问题

多条件的 WHERE 子句是可以的,但是并不优雅。

例如:

$results = User::where('this', '=', 1)
    ->where('that', '=', 1)
    ->where('this_too', '=', 1)
    ->where('that_too', '=', 1)
    ->where('this_as_well', '=', 1)
    ->where('that_as_well', '=', 1)
    ->where('this_one_too', '=', 1)
    ->where('that_one_too', '=', 1)
    ->where('this_one_as_well', '=', 1)
    ->where('that_one_as_well', '=', 1)
    ->get();

是否有比这更好的实现方式吗?

答案

在 Laravel 5.3 你可以传递一个 wheres 数组:

$query->where([
    ['column_1', '=', 'value_1'],
    ['column_2', '<>', 'value_2'],
    [COLUMN, OPERATOR, VALUE],
    ...
])

自2014年6月起,你可以将数组传递给 where
只要你想要所有 wheres 使用 and 运算符,你就可以用这种方式对它们进行分组:

$matchThese = ['field' => 'value', 'another_field' => 'another_value', ...];

// 如果你需要 or where 语句,同理:
$orThose = ['yet_another_field' => 'yet_another_value', ...];

然后:

$results = User::where($matchThese)->get();

// with another group
$results = User::where($matchThese)
    ->orWhere($orThose)
    ->get();

上面代码的查询语句如下:

SELECT * FROM users
  WHERE (field = value AND another_field = another_value AND ...)
  OR (yet_another_field = yet_another_value AND ...)

其他选项

查询作用域可以帮助你把代码变的更具可读性。

《Laravel 中文文档》

在你的模型中,创建像这样的作用域方法:

public function scopeActive($query)
{
    return $query->where('active', '=', 1);
}

public function scopeThat($query)
{
    return $query->where('that', '=', 1);
}

然后,你就可以在构建查询时调用此方法:

$users = User::active()->that()->get();

参考:https://stackoverflow.com/questions/1932...

本文为 Wiki 文章,邀您参与纠错、纰漏和优化
讨论数量: 8

传array有点类似于tp32的查询构造方式,从语义上看丢失了原来QueryBuilder的语言特性,引入了数组,在函数调用时很可能造成参数混乱。从代码美观来看, :flushed:大家是喜欢十几行两层方括号的代码呢,还是喜欢十几行where子句呢?

5年前 评论
Summer

@Kamicloud 还有一些场景下数组传参会比较方便,例如页面上提供复杂的过滤搜索,参数都是通过 URL 传参进来的数组:

file

5年前 评论

whereBetween的怎么玩? :eyes:

4年前 评论

select * from table1,table2 where table1.rid = table2.rid and table2.id = 1;这样的sql怎么用laravel写出来 。网上能找到的全是单表查询,找到一个JOIN的也不能用。

4年前 评论

@dawen 你试试是不是这个效果

/**
     * table1和table2关联
     * @return mixed
     */
    public function linkTableTwo(){
        return $this->hasOne(TableTwo::class,'rid','rid');
    }

    /**
     * 获取table1和table2
     */
    public function testInfo(){
        $id=1;
        TableOne::whereHas('linkTableTwo',function($query) use ($id){
           $query->where('id',$id);
        })->with('linkTableTwo')->get();
    }
4年前 评论

用了下面的这个,但是效果不太对

User::where(['id' => 1, 'sex' => 0])->orWhere(['id' => 2, 'sex' => 1])->get();
array:1 [▼
  0 => array:3 [▼
    "query" => "select * from `bl_users` where (`id` = ? and `sex` = ?) or (`id` = ? or `sex` = ?)"
    "bindings" => array:4 [▶]
    "time" => 3.11
  ]
]

我是想要这样的效果

"select * from `bl_users` where (`id` = ? and `sex` = ?) or (`id` = ? and `sex` = ?)"

这样的怎么可以实现

4年前 评论
Complicated

数组也好还是builder也好,我感觉还是看情况和个人习惯使用(个人感觉,数组的灵活度还是不如builder的)

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!