美文网首页PHP开发PHP经验分享程序猿的进阶屋
Laravel/Lumen Model中自定义函数踩坑必看

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

作者: 郝开心信札 | 来源:发表于2017-11-12 08:43 被阅读236次

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

    相关文章

      网友评论

        本文标题:Laravel/Lumen Model中自定义函数踩坑必看

        本文链接:https://www.haomeiwen.com/subject/oelnmxtx.html