Laravel 4:多对多关系(插入)

6

我在数据库中有这些表:

[posts, cats (categories), posts_cats (pivote)]

“posts”表和“cats”表之间的关系是多对多

我在模型类中声明了这种关系:

//Post.php
public function cats()
{
    return $this->belongsToMany('cats');
}



//Cats.php
public function post()
{
    return $this->belongsToMany('posts');
}

问题是,如何在多个分类中插入新的帖子?
谢谢。

1
你的数据透视表应该被称为:post_cat(单数 vs 复数)。你可以使用另一个数据透视表名称,但是你需要将该表的名称作为第二个参数提供给belongsToMany()方法。 - Ilyes512
3个回答

15

假设您知道文章的ID,那么可以像这样附加单个类别:

Post::find($post_id)->cats()->attach($cat_id);

或者像这样附加多个cat:

$cat_ids = array(1,2,3,4);
Post::find($post_id)->cats()->attach($cat_ids);

如果您已经将Post模型对象存储在一个变量中,比如说$post:
$post->cats()->attach($cat_id);

// Or with multiple
$cat_ids = array(1,2,3,4);
$post->cats()->attach($cat_ids);

如果您有一个单一的类别作为模型对象,比如 $model:
$post->cats()->save($model);

请注意@Gadoma的回答。虽然不是错的,但如果您想向已有类别的帖子添加类别,则应使用attach()而不是sync()。当使用Sync()时,它将删除所有未提供给它的其他内容。
编辑:
所以,如果您正在创建新的帖子,那么您可能正在做以下事情:
$post = new Post;
$post->title = 'The title';
$post->something_else = 'Lorem';
$post->save();

//So now you have both the model object (the $post variable) and the id ($post->id).

$post->cats()->attach($cat_ids);

如果我不知道文章ID(添加带有其类别的新文章)呢? - mwafi

1
当您插入文章时,然后迭代分类并将它们附加到新文章。类似于这样:
// $categories is an array of the categories to attach
foreach ($category_id in $categories) {
    // Get a category object 
    $category = CategoryModel::find($category_id);
    // $post is the new post 
    $post->cats()->attach($category);
}

我希望它能对你有所帮助。

1

来自文档 http://laravel.com/docs/eloquent#inserting-related-models

插入相关模型(多对多)

[...]

您还可以使用sync方法来附加关联模型。 sync 方法接受一个ID数组,用于放置在中间表上。此操作完成后,仅在该数组中的ID将位于模型的中间表上:

这里有一个代码示例:

$post = new Post(array('field1'=>'value1','fieldN'=>'valueN')) //example create new post
$categoryIds = array(1,3,4,5); //ids of (cats) categories you want the post to go into
$post->cats()->sync($categoryIds); //synchronise pivot table content with $categoryIds

显示错误:"MassAssignmentException title",请参考 $post = new Post(array('title' => Input::get('title'), 'topic'=>Input::get('topic'))); - mwafi
这个,太棒了!5.1 文档链接: http://laravel.com/docs/5.1/eloquent-relationships#syncing-for-convenience - SchizoDuckie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接