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条)

报告相同问题?

悬赏问题

  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图