dou7466 2017-06-04 03:02 采纳率: 0%
浏览 110
已采纳

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

I want to write a dynamic update query in Laravel which accepts arguments and can be used in whole project.

Following is my Controller function:

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!');;

    }

Below is my Model function:

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

The only problem here is that I cannot store the value ('city_id',1) in the $wher variable. This is the screenshot of the error: link to the image file

Is there any other way to do this. Please Help.

  • 写回答

3条回答 默认 最新

  • doulang6013 2017-06-04 05:13
    关注

    The where method accepts an array of conditions.

    $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);
    }
    

    You can also set multiple conditions.

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

    Edit

    This is the default where method

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

    Setting the fourth parameter to or will make the condition orWhere.

    Example

    $conditions = [
        ['city_id', '=', '1'],
        ['test', '=', 'test', 'or'],
    ];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 HFSS设计小型化180度耦合器
  • ¥15 使用CInternetSession,CHttpFile读取网页文件时有些电脑上会卡住怎么办?
  • ¥15 水下机器人的半物理仿真研究
  • ¥15 微服务假死,一段时间后自动恢复,如何排查处理
  • ¥50 webrtc-streamer TCP rtsp
  • ¥15 cplex运行后参数报错是为什么
  • ¥15 之前不小心删了pycharm的文件,后面重新安装之后软件打不开了
  • ¥15 vue3获取动态宽度,刷新后动态宽度值为0
  • ¥15 升腾威讯云桌面V2.0.0摄像头问题
  • ¥15 关于Python的会计设计