【发布时间】:2014-07-21 02:21:45
【问题描述】:
MySql 在尝试创建模型的新实例时抛出错误。 user_id 字段有效,我尝试手动设置,但也没有用。存在 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();
});
}
【问题讨论】:
标签: php mysql laravel laravel-4 eloquent