gpt4 book ai didi

php - 为什么我的 Laravel 4 种子脚本会生成不正确的插入查询?

转载 作者:行者123 更新时间:2023-11-29 23:45:54 25 4
gpt4 key购买 nike

我已经开始使用 Laravel 4 并被一个奇怪的问题难住了。我为表编写了迁移,成功创建了表。

<?php    
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateOrgRoles extends Migration {
protected $tableName ;

function __construct(){
$this->tableName = "org_roles";
}
public function up()
{
Schema::dropIfExists($this->tableName);
Schema::create($this->tableName, function(Blueprint $table)
{
$table->increments('id');
$table->string('role_name')->unique();
$table->mediumText('role_description')->nullable();
$table->timestamps();
});
}

public function down(){
Schema::drop($this->tableName);
}
}

然后我继续为该表编写一个简单的模型 OrgRole.php

<?php

class OrgRole extends Eloquent {
protected $tableName;
protected $fillable = ['role_name', 'role_description'];

function __construct(){
$this->tableName = 'org_roles';
}
}

然后我为文件编写了种子,如下所示

<?php

class OrgRolesTableSeeder extends Seeder {

protected $tableName;

function __construct(){
$this->tableName = "org_roles";
}

public function run() {
$defaultRoles = array(
[
'role_name' => 'guest',
'role_description' => 'the most basic one of all'
]
);

foreach ( $defaultRoles as $role ) {
OrgRole::create( $role );
}
}

}

现在,当我运行种子命令时,形成的插入查询是错误的,并且播种失败

» php artisan db:seed                                                                                        
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1364 Field 'role_name' doesn't have a default value (SQL: insert into `or
g_roles` (`updated_at`, `created_at`) values (2014-09-21 01:57:14, 2014-09-21 01:57:14))

[PDOException]
SQLSTATE[HY000]: General error: 1364 Field 'role_name' doesn't have a default value

有人可以帮助我理解我做错了什么吗?

最佳答案

  1. 从播种器和模型文件中删除构造函数。在播种器中没有必要,因为您在 run() 方法中调用模型 OrgRole

  2. 在模型文件中,将 protected $tableName; 替换为 protected $table = 'org_roles';

然后尝试再次运行 php artisan db:seed。 (请确保删除已播种的所有记录,否则对 role_name 的独特要求将导致播种失败。)

关于php - 为什么我的 Laravel 4 种子脚本会生成不正确的插入查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25955101/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com