【发布时间】:2016-10-27 09:48:26
【问题描述】:
这个问题有already been asked many times,我浏览了所有答案,但没有一个能解决我遇到的错误。
我正在使用 Laravel 5.2
我有 2 个表格 - 分类和类别。当我想创建分类时,我收到错误消息:
SQLSTATE[23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败(
myclassified.classifieds,CONSTRAINTclassifieds_category_id_foreignFOREIGN KEY (category_id) REFERENCEScategories(id))
迁移文件定义如下:
对于classifieds 表:
public function up()
{
Schema::create('classifieds', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('description');
$table->string('price');
$table->timestamps();
});
}
public function down()
{
Schema::drop('classifieds');
}
对于categories 表:
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
public function down()
{
Schema::drop('categories');
}
并添加外键,
public function up()
{
Schema::table('classifieds', function(Blueprint $table) {
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories');
});
}
public function down()
{
Schema::table('classifieds', function(Blueprint $table) {
$table->dropForeign('classifieds_category_id_foreign');
});
}
模型是:
Classified模特:
class Classified extends Model
{
protected $table = 'classifieds';
protected $fillable = ['title', 'category_id', 'description', 'price'];
protected $hidden = [];
public function category(){
return $this->belongsTo('App\Category');
}
}
和Category 模型:
class Category extends Model
{
protected $table = 'categories';
protected $fillable = ['name'];
protected $hidden = [];
public function classifieds(){
return $this->hasMany('App\Classified');
}
}
控制器中的store方法是这样定义的:
public function store(Request $request)
{
$title = $request->input('title');
$category_id = $request->input('category_id');
$description = $request->input('description');
$price = $request->input('price');
Classified::create([
'title' => $this->title,
'category_id' => $this->category_id,
'description' => $this->description,
'price' => $this->price
]);
return \Redirect::route('classifieds.index')
->with('message', 'Ad created');
}
我在数据库设置中的错误是什么?
【问题讨论】:
标签: php mysql laravel laravel-5.2