简体   繁体   English

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

[英]Correct way to define many to many relationship with Laravel

I have two models: 我有两个型号:

BlogPost model: BlogPost模型:

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: 和BlogCategory模型:

class BlogCategory extends Model {

    protected $table = 'blog_categories';


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

}

Is it the correct way of using the 3rd and 4th parameters in belongsToMany() for the 2 models ? 对于2个模型,在belongsToMany()中使用第3个和第4个参数是否正确?

It seems to be working because the pivot table is filled when attach() method is called: 它似乎正在工作,因为在调用attach()方法时填充了数据透视表:

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

but fails when using detach() with this error: 但是在使用detach()时出现此错误:

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

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

You have call detach on the relation instance, not the collection. 您在关系实例上有调用detach ,而不是集合。

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

BTW, it seems you want to remove all categories. 顺便说一句,似乎你想要删除所有类别。 You can achieve that by simply not passing anything to the detach method: 您可以通过简单地不将任何内容传递给detach方法来实现:

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

Much more efficient. 效率更高。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM