[英]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.