如何删除基于多个where条件的记录作为laravel中的数组

Kir*_*ran 3 php arrays delete-record laravel

我在docs和堆栈交换中搜索了几天,有没有什么方法可以实际传递一个包含多个条件的数组来删除Laravel 4.2中的记录?

我想实现类似下面的东西

DELETE FROM `employees` WHERE user_id = 5 AND dept_id = 5
Run Code Online (Sandbox Code Playgroud)

为此我可以做下面的事情吗?

$whereArray = array('user_id'=>5,'dept_id'=>5);

return DB::table('employees')->where($whereArray)->delete();
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用多个条件来实现这一点.但是每次新条件到来时我都要重写这个功能.而且我也不能将此功能用作动态功能.

那请帮帮我吧?如何使用数组实现这一目标?

pat*_*cus 10

您不能直接传入数组,但可以处理数组:

$whereArray = array('user_id' => 5,'dept_id' => 5);

$query = DB::table('employees');
foreach($whereArray as $field => $value) {
    $query->where($field, $value);
}
return $query->delete();
Run Code Online (Sandbox Code Playgroud)

此功能可以提取到函数中,甚至是模型范围,它接受您的数组并构建并将查询返回给您.

例如,如果您有一个Employee型号:

class Employee extends Eloquent {

    public function scopeWhereArray($query, $array) {
        foreach($array as $field => $value) {
            $query->where($field, $value);
        }
        return $query;
    }

}
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

$whereArray = array('user_id' => 5,'dept_id' => 5);

return Employee::whereArray($whereArray)->delete();
Run Code Online (Sandbox Code Playgroud)

编辑

如果您希望能够为运营商提供服务,您只需要更改阵列的格式:

$whereArray = array(
    array(
        'field' => 'user_id',
        'operator' => '=',
        'value' => 5
    ),
    array(
        'field' => 'dept_id',
        'operator' => '=',
        'value' => 5
    ),
    array(
        'field' => 'salary',
        'operator' => '<',
        'value' => 5000
    )
);

return Employee::whereArray($whereArray)->delete();
Run Code Online (Sandbox Code Playgroud)

你需要更新你的功能:

class Employee extends Eloquent {

    public function scopeWhereArray($query, $array) {
        foreach($array as $where) {
            $query->where($where['field'], $where['operator'], $where['value']);
        }
        return $query;
    }

}
Run Code Online (Sandbox Code Playgroud)