【问题标题】:Laravel 4: many to many (insertion)Laravel 4:多对多(插入)
【发布时间】:2014-07-17 11:10:12
【问题描述】:

我在数据库中有这些表:

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

posts 表和猫的关系是多对多的

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

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



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

问题是,如何插入具有多个类别的新帖子?

谢谢,

【问题讨论】:

  • 您的数据透视表应称为:post_cat(单数与复数)。您可以使用替代的数据透视表名称,但是您需要将该表的名称作为第二个参数提供给 belongsToMany() 方法。

标签: php mysql laravel laravel-4


【解决方案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);
}

希望对你有帮助。

【讨论】:

    【解决方案2】:

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

    插入相关模型(多对多)

    [...]

    您也可以使用同步方法附加相关模型。同步 方法接受要放置在数据透视表上的 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 标题”指的是 $post = new Post(array('title' => Input::get('title'), 'topic'=>Input::get( '主题')));
    • 这个,这么多! 5.1 文档链接:laravel.com/docs/5.1/…
    【解决方案3】:

    假设您知道帖子的 id,那么您可以像这样附加一只猫:

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

    或者像这样附加多只猫:

    $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's answer。它没有错,但是如果您想将类别添加到已经有类别的帖子中,那么您应该使用 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 怎么办(添加新帖子及其类别)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 2014-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    • 2011-06-02
    相关资源
    最近更新 更多