1 回答
TA贡献1802条经验 获得超5个赞
在 Laravel 中为 ManyToMany 关系使用数据透视表时,您应该将关联的标签和类别与 Post 模型分离,而不是按照文档删除它们
此外,您的控制器代码正在删除标签和类别模型,而不是会破坏任何关联的关联附加到这些标签和类别的其他帖子。
这是
在您的tags迁移中执行此操作的正确方法的示例
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->bigIncrements('id');
// Any other columns goes here
$table->timestamps();
});
Schema::create('post_tag', function (Blueprint $table) {
$table->bigInteger('post_id');
$table->bigInteger('tag_id');
// ensures a specific post can be associated a specific tag only once
$table->primary(['post_id', 'tag_id']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('post_tag');
Schema::dropIfExists('tags');
}
为类别迁移做同样的事情在你的 Eloquent 模型中
指定ManyToMany关系,像这样
class Post extends Model
{
public function tags()
{
return $this->belongsToMany('App\Tag');
}
public function categories()
{
return $this->belongsToMany('App\Category');
}
}
现在,当将标签/类别与帖子相关联时,请使用该attach方法
$post = Post::create([]); // this is only sample code, fill your data as usual
$tag = Tag::create([]);
$category = Category::create([]);
// You can either attach by the model itself or ID
$post->tags()->attach($tag);
$post->categories()->attach($category);
最后在销毁 Post 模型时,只需解除与标签和类别的关系,而不是使用detach 像这样的方法删除它们
public function destroy(Post $post)
{
$post->categories()->detach();
$post->tags()->detach();
$post->delete();
return redirect('admin/post')->with('message','Deleted Sucessfully');
}
- 1 回答
- 0 关注
- 296 浏览
添加回答
举报