must be of the type array, string given -- Laravel 查询数据库报错

问题

使用Laravel的Model类查询数据库时报错:

FatalThrowableError in Grammar.php line 107:
Type error: Argument 1 passed to Illuminate\Database\Grammar::columnize() must be of the type array, string given, called in /myproject /vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/Grammar.php on line 108


解决过程

根据报错"must be of the type array, string given", 预判是传递参数的问题, 开始验证这个想法.


尝试01: 测试传递参数是否有问题

原来的路由是:

Route::match(['get','post'],'/message/edit/{id}',function($id){
    $message = new App\Message();
    return $message->edit($id);
});

修改为:

Route::match(['get','post'],'/message/edit/{id}',function($id){
    return $id;
});

可以跑通;


尝试02: 测试Model的方法是否获取到参数

Model中的edit()方法:

public function edit($id){
  return $id;
}

可以跑通. 那么就不是传递参数的问题.


尝试03: 缩小范围后继续排错

排除参数问题后, 检查代码逻辑.

发现是将$data = $this->where('id',$id)->first();错误写成了
$data = $this->first($id);


弥补知识漏洞

总结了Model类查询数据库的方法:

  • 查询单行
    • 主键查询: ->find($id)
    • where条件: ->where('id',6)->first()
  • 查询多行
    • where条件: where('id','>',5)->get(['title','id'])
  • 查询所有
    • ->all(), 或者筛选提取的字段->all(['title','id'])
    • ->get(), 或者筛选提取的字段->get(['title','id'])

文章历史

  • 2016/10/22 (第一次发布)

如果你觉得我的文章对你有用, 请打个"喜欢", 或者给些改进的建议 _

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容