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

Correct way to define many to many relationship with Laravel

我有两个模型:

BlogPost模型:

class BlogPost extends Model {

    protected $table = 'blog_posts';

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

}

和 BlogCategory 模型:

class BlogCategory extends Model {

    protected $table = 'blog_categories';


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

}

这两个模型在 belongsToMany() 中使用第 3 个和第 4 个参数的方法是否正确?

它似乎在工作,因为当调用 attach() 方法时,枢轴 table 被填充:

if ( is_array( $request->get('categories') ) && count( $request->get('categories') ) ) {
            $post->categories()->attach( $request->get('categories') );
        }

但在使用 detach() 时失败并出现此错误:

调用未定义的方法Illuminate\Database\Eloquent\Collection::detach()

foreach ( $post->categories as $category ) {
            $post->categories->detach( $category->id );
            echo "<br />" . $category->id;
        }

您在关系实例上调用了 detach,而不是集合。

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

顺便说一句,您似乎想删除所有类别。您可以通过简单地不将任何内容传递给 detach 方法来实现:

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

更有效率。