【问题标题】:Laravel 5 - Call to undefined method App\Role::firstOrCreate()Laravel 5 - 调用未定义的方法 App\Role::firstOrCreate()
【发布时间】:2017-11-01 11:36:45
【问题描述】:

当我尝试运行我的数据库种子时,我在 Laravel 5.5 中遇到了一个非常奇怪的错误。当我运行php artisan db:seed --class=RoleSeeder 时,出现以下错误:

调用未定义的方法 App\Role::firstOrCreate()

这是我的RoleSeeder 课程:

<?php

use Illuminate\Database\Seeder;


class RoleSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {


        //Application User: All users have this role be default
        $r = \App\Role::firstOrCreate(['name'=>'app-user'],
            [
                'name'         => 'app-user',
                'display_name' => 'All users of the application',
                'description'  => 'Uses the application',
            ]
        );


    }
}

我在许多 Laravel 5.4 项目中多次使用这个 sn-p 代码,没有问题。我在另一个 Laravel 5.5 项目上发生了这个错误,该项目神秘地自行解决了,但现在我无法弄清楚为什么在一个新项目上再次发生这种情况。

当我在 laravel tinker(一个交互式 php 会话)中运行上面的 sn-p 代码时,它可以正常工作。

我已验证firstOrCreate 函数存在于 vendor/laravel/src/Illuminate/Database/Eloquent/Builder.php.

我的Role 类是直接从Entrust 库文档中复制而来的:

<?php namespace App;

use Zizaco\Entrust\EntrustRole;

class Role extends EntrustRole
{
}

当我将Role 类更改为直接扩展Model 时,db:seed 命令运行良好。但是当Role扩展EntrustRole时出现错误,定义如下:

class EntrustRole extends Model implements EntrustRoleInterface
{
//..

我现在将实施一个解决方法,但如果有人能解释为什么这在 php artisan tinker 中可以正常工作,但在作为播种机运行时却不行,那就太好了。

编辑: 经过进一步调查,它似乎只是非常零星地发生:

user@localmachine:/var/www/MyProject$ sudo php artisan cache:clear
Cache cleared successfully.
user@localmachine:/var/www/MyProject$ sudo php artisan db:seed
Seeding: RoleSeeder


  [BadMethodCallException]
  Call to undefined method App\Role::firstOrCreate()


user@localmachine:/var/www/MyProject$ sudo php artisan cache:clear
Cache cleared successfully.
user@localmachine:/var/www/MyProject$ sudo php artisan cache:clear
Cache cleared successfully.
user@localmachine:/var/www/MyProject$ sudo php artisan cache:clear
Cache cleared successfully.
user@localmachine:/var/www/MyProject$ sudo php artisan cache:clear
Cache cleared successfully.
user@localmachine:/var/www/MyProject$ sudo php artisan db:seed
Seeding: RoleSeeder
Seeding: UserSeeder

【问题讨论】:

    标签: php laravel laravel-5.5


    【解决方案1】:

    将缓存驱动切换到redis后,问题现已解决。我现在意识到这也可能是“神秘地”修复了我的另一个 Laravel 5.5 项目(当我将缓存驱动程序切换到 memcached 时)。似乎是 Laravel 5.5 和文件缓存驱动程序的错误

    【讨论】:

      猜你喜欢
      • 2020-01-14
      • 2016-06-05
      • 2020-01-18
      • 1970-01-01
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-10
      相关资源
      最近更新 更多