【发布时间】:2018-11-12 05:55:44
【问题描述】:
这是我的帖子表
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->integer('category_id')->unsigned()->index();
$table->integer('photo_id')->default(0)->unsigned()->index();
$table->string('title');
$table->text('body');
$table->timestamps();
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
});
}
这是我的用户表
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->integer('role_id')->index()->unsigned()->nullable();
$table->integer('photo_id')->index()->default(0);
$table->boolean('is_active')->default(0);
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
这些是关系
public function posts() {
return $this->hasMany('App\Post');
}
public function user() {
return $this->belongsTo('App\User');
}
删除用户代码
public function destroy($id)
{
$user = User::findOrFail($id);
if($user->photo_id !== 0) {
unlink(public_path() . $user->photo->path);
}
$user->delete();
Session::flash('deleted_user', 'The user has been deleted.');
return redirect('/admin/users');
}
删除帖子代码
public function destroy($id)
{
$post = Post::findOrFail($id);
if($post->photo_id !== 0) {
unlink(public_path() . $post->photo->path);
}
$post->delete();
return redirect('/admin/posts');
}
我在删除用户时尝试删除与该用户相关的所有帖子。 为此,我在帖子表中使用了外部引用约束,如上所示 但是当我删除用户时它不起作用。帖子还在。 我不知道我做错了什么
【问题讨论】:
-
你的删除代码是什么?
-
见上文我在问题中添加了它
-
你用的是什么版本的 Laravel,什么版本的 MySQL?
标签: php mysql laravel laravel-5 migration