【发布时间】: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