在调用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
, 此时也可以成功,但不是通过访问你的自定义函数成功的,直接调用属性而已。
网友评论