我想在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);
}
这里唯一的问题是我无法将值('city_id',1)存储在$ wher变量中。这是错误的屏幕截图: link to the image file
还有其他方法可以做到这一点。请帮助。
答案 0 :(得分:2)
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'],
];
答案 1 :(得分:1)
你不能这样做
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);
答案 2 :(得分:0)
您的代码并不完全符合Laravel的风格,如果Eloquent / Query Builder的标准功能可以轻松解决这些任务,您为什么要创建单独的静态函数?
雄辩的例子:
应用程序/ 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
]);
这比以不可理解的方式做类似事情的功能更容易阅读,理解和支持。