Php 使用Laravel定义多对多关系的正确方法

Php 使用Laravel定义多对多关系的正确方法,php,laravel,orm,laravel-5,many-to-many,Php,Laravel,Orm,Laravel 5,Many To Many,我有两种型号: BlogPost模型: class BlogPost extends Model { protected $table = 'blog_posts'; public function categories() { return $this->belongsToMany( 'BlogCategory', 'blog_category_post', 'post_id', 'category_id' ); } } class

我有两种型号:

BlogPost模型:

class BlogPost extends Model {

    protected $table = 'blog_posts';

    public function categories()
    {
        return $this->belongsToMany( 'BlogCategory', 'blog_category_post', 'post_id', 'category_id' );
    }

}
class BlogCategory extends Model {

    protected $table = 'blog_categories';


    public function posts()
    {
        return $this->belongsToMany( 'BlogPost', 'blog_category_post', 'category_id', 'post_id' );
    }

}
和博客类别模型:

class BlogPost extends Model {

    protected $table = 'blog_posts';

    public function categories()
    {
        return $this->belongsToMany( 'BlogCategory', 'blog_category_post', 'post_id', 'category_id' );
    }

}
class BlogCategory extends Model {

    protected $table = 'blog_categories';


    public function posts()
    {
        return $this->belongsToMany( 'BlogPost', 'blog_category_post', 'category_id', 'post_id' );
    }

}
对于这两个模型,使用belongtomany()中的第3和第4个参数是否正确

由于调用attach()方法时数据透视表已填充,因此它似乎可以正常工作:

if ( is_array( $request->get('categories') ) && count( $request->get('categories') ) ) {
            $post->categories()->attach( $request->get('categories') );
        }
但在使用detach()时失败,出现以下错误:

调用undefined方法Illumb\Database\Eloquent\Collection::detach()

foreach($post->categories as$category){
$post->categories->detach($categority->id);
回显“
”$category->id; }
您对关系实例而不是集合调用了
分离

foreach($post->categories as$category){
$post->categories()->detach($category->id);
//               ^^
}

顺便说一句,你似乎想删除所有类别。只需不向
detach
方法传递任何内容即可实现此目的:

$post->categories()->detach();

效率更高。

您是否尝试过
$post->categories()->detach($category->id)
$post->categories
返回一个集合,而
$post->categories()
返回一个关系。此外,如果OP正在修剪所有关系,然后插入关系,那么“sync()”方法可能会更简洁。只需传递一组外键,Eloquent将通过剪枝和插入来同步数据透视表。