首页 文章

正确的方式来定义与Laravel的多对多关系

提问于
浏览
1

我有两个型号:

BlogPost model:

class BlogPost extends Model {

    protected $table = 'blog_posts';

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

}

and BlogCategory model:

class BlogCategory extends Model {

    protected $table = 'blog_categories';


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

}

对于2个模型,在belongsToMany()中使用第3个和第4个参数是否正确?

它似乎正在工作,因为在调用attach()方法时填充了数据透视表:

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

但是在使用detach()时出现此错误:

Call to undefined method Illuminate\Database\Eloquent\Collection::detach()

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

1 回答

  • 3

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

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

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

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

    效率更高 .

相关问题