繁体   English   中英

Laravel 5.4:将'Where'子句存储在变量中

[英]Laravel 5.4: Storing the 'Where' clause in a variable

我想在Laravel中编写一个动态更新查询,该查询接受参数并可以在整个项目中使用。

以下是我的控制器功能:

public function editquery(Request $request)
    {

    $city_id   = $request->input('city_id');    
    $city_name = $request->input('city_name');   

    $tbl  = 'city';    
    $data = ['city_name'=>$city_name];
    $wher = ('city_id',1);

    General_model::editrecord($data,$wher,$tbl);

    return redirect()->action('Admin_controller@cities_page')->with('status','Record Updated Successfully!');;

    }

下面是我的模型函数:

public static function editrecord($data,$wher,$tbl)
    {
      return DB::table($tbl)->where($wher)->update($data);
    }

唯一的问题是我无法在$ wher变量中存储值('city_id',1)。 这是错误的屏幕截图: 链接到图像文件

还有其他方法可以做到这一点。 请帮忙。

where方法接受条件数组。

$table  = 'city';
$conditions = [
    ['city_id', '=', '1']
];
$data = ['city_name' => $city_name];

General_model::editRecord($table, $conditions, $data);

// In your model

public static function editRecord($table, $conditions, $data)
{
    return DB::table($table)->where($conditions)->update($data);
}

您还可以设置多个条件。

$conditions = [
    ['city_id', '=', '1'],
    ['test', '=', 'test'],
];

编辑

这是默认的where方法

where($column, $operator = null, $value = null, $boolean = 'and')

将第四个参数设置为or将使条件orWhere

$conditions = [
    ['city_id', '=', '1'],
    ['test', '=', 'test', 'or'],
];

你做不到

public static function editrecord($data,$wher,$tbl)
{
  return DB::table($tbl)->where($wher)->update($data);
}

因为,函数where 它需要2或3个参数,而不仅仅是1个参数。

您将必须像这样传递两个参数

public static function editrecord($data, $where_column, $where_val, $tbl)
{
  return DB::table($tbl)->where($where_column, $where_val)
                        ->update($data);
}

然后,在您的控制器功能中

$where_column = 'city_id';
$where_val = 1;

General_model::editrecord($data,$where_column,$where_val,$tbl);

您的代码并非完全采用Laravel的样式,如果Eloquent / Query Builder的标准功能可以轻松解决此类任务,为什么还要创建一个单独的静态函数?

雄辩的例子:

app / City.php

<?php
class City extends Model {
    protected $table = 'city';
    protected $primaryKey = 'city_id';
    protected $fillable = ['city_name'];
}

在您的控制器中:

City::findOrFail($city_id)->update([
    'city_name' => $city_name
]);

查询生成器示例:

DB::table('city')->where(['city_id' => $city_id])->update([
    'city_name' => $city_name
]);

这比以难以理解的方式执行类似操作的功能更容易阅读,理解和支持。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM