在尝试创建模型的新实例时,MySql会抛出错误。 user_id
字段有效,我已尝试手动设置,但它也无效。身份1
的用户已存在。
错误:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`production_paperclip`.`widgets`, CONSTRAINT `widgets_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION) (SQL: insert into `widgets` (`updated_at`, `created_at`) values (2014-07-21 02:14:12, 2014-07-21 02:14:12))
查询:
\Widget::create(array(
'title' => \Lang::get('widget.news_localizer.install.title'),
'strictName' => self::strictName,
'userSettings' => null,
'description' => \Lang::get('widget.news_localizer.install.description'),
'bodyTemplateName' => 'admin.dashboard.widgets.news_localizer.index',
'user_id' => \Auth::id(),
));
型号:
class Widget extends \Eloquent
{
use SoftDeletingTrait;
protected $fillable = array('*');
/**
* Get the user which installed the widget
* @return Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo('User');
}
}
迁移:
public function up()
{
Schema::create('widgets', function(Blueprint $table)
{
$table->increments('id');
// Name
$table->string('title', 256);
$table->index('title');
// Strict name
$table->string('strictName')->unqiue();
// User settings
$table->text('userSettings')->nullable();
// A short description
$table->string('description')->nullable();
// Body template name
$table->string('bodyTemplateName');
// User
$table->integer('user_id')->length(10)->unsigned();
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('no action');
$table->timestamps();
$table->softDeletes();
});
}
答案 0 :(得分:4)
在Widget
模式更改
protected $fillable = array('*');
到
protected $guarded = array('id', 'created_at', 'updated_at');
或
protected $fillable = array('title', 'strictName', 'userSettings', 'description', 'bodyTemplateName', 'user_id');
换句话说,您必须明确指定可填写字段(白名单)或保护字段(黑名单)。 *
仅适用于$guarded
,而非$fillable
,错误消息清楚地表明了这一点。您只填充了时间戳字段:
insert into `widgets` (`updated_at`, `created_at`)
values (2014-07-21 02:14:12, 2014-07-21 02:14:12)