我在我的laravel應用程序中遇到此錯誤。完整性約束違規:1452無法添加或更新子行:外鍵約束失敗(Laravel應用程序)
這些都是表:
後
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('content');
$table->timestamps();
$table->integer('user_id')->unsigned();
});
分類
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Post_Category
Schema::create('post_category', function (Blueprint $table) {
$table->integer('post_id')->unsigned()->unique()->nullable();
$table->integer('cat_id')->unsigned()->unique()->nullable();
$table->timestamps();
});
外鍵
Schema::table('posts', function (Blueprint $table) {
$table->foreign('id')->references('post_id')->on('post_category')->onDelete('cascade');
});
Schema::table('categories', function (Blueprint $table) {
$table->foreign('id')->references('cat_id')->on('post_category')->onDelete('cascade');
});
這裏我的模型
class Categorie extends Model
{
protected $table = 'categories';
public function posts() {
return $this->hasMany('App\PostCategory');
}
}
...
class Post extends Model
{
public function author() {
return $this->belongsTo('App\User', 'user_id');
}
public function featuredImage() {
return $this->belongsTo('App\Media', 'media_id');
}
public function categories() {
return $this->hasMany('App\PostCategory');
}
}
...
class PostCategory extends Model
{
protected $table = 'post_category';
}
這裏控制器
店鋪分類:
public function store(StoreCategory $request)
{
$category = new Categorie;
$category->name = $request->input('name');
$category->save();
return redirect('/admin/categories')->with('status', 'New category created!');
}
店後
public function store(StorePost $request)
{
$post = new Post;
$post->title = $request->input('title');
$post->content = $request->input('content');
$post->media_id = $request->input('media_id');
$post->user_id = $request->input('user_id');
$post->save();
return redirect('/admin/posts')->with('status', 'New post created!');
}
有了這個錯誤
SQLSTATE [2300 0]:完整性約束違規:1452無法添加或更新子行:外鍵約束失敗(
the_film_corner
。tfc_categories
,約束categories_id_foreign
外鍵(id
)參考文獻tfc_post_category
(cat_id
)ON DELETE CASCADE)(SQL:插入tfc_categories
(name
,updated_at
,created_at
)值(新聞,2017年2月26日14時51分15秒,2017-02- 26 14時51分15秒))
感謝
感謝Samuele的幫助。 –