Laravel/Lumen Model中自定义函数踩坑必看

栏目: PHP · 发布时间: 8年前

内容简介:Laravel/Lumen Model中自定义函数踩坑必看

在调用model里的自定义函数时,经常会出现以下错误:

    (1/1) BadMethodCallException     Call to undefined method App/Models/QueryBuilder::isAdmin()

网上大多例子都使用 User::find()->func() 的方式,但是我用 where() 时,Laravel一直以上报错。

这里有几点注意:

  • User::where() 相当于 User::query->where() , User下发现自己没有 where() ,就去调用一些magic

  • User::where() 返回的是 QueryBuilder 类型,当调用 first() 返回 对象get() 返回的是 Collection 类型。要调用model里的函数需要在对象上调用,即跟在 first() 或者 find() 后面

最后,上代码

        // User.php         public function isAdmina()         {             return $this->isAdmin;         }          // Controller.php         // an example of "find()"         User::find(274)->isAdmina();                  // an example of "where()"         User::where('username', $user)->first()->isAdmina();

注意到上面的例子中 isAdmina() 只是返回数据表中的 isAdmin 字段,所以当你在 Controller 中也可以用 User::where('username', $user)->first()->isAdmin , 此时也可以成功,但不是通过访问你的自定义函数成功的,直接调用属性而已。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Parsing Techniques

Parsing Techniques

Dick Grune、Ceriel J.H. Jacobs / Springer / 2010-2-12 / USD 109.00

This second edition of Grune and Jacobs' brilliant work presents new developments and discoveries that have been made in the field. Parsing, also referred to as syntax analysis, has been and continues......一起来看看 《Parsing Techniques》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码