Laravel 4:多对多(插入)

mwa*_*afi 6 php mysql laravel laravel-4

我在DB中有这些表:

[posts, cats (categories), posts_cats (pivote)]
Run Code Online (Sandbox Code Playgroud)

邮政桌和猫之间的关系是多对多的

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

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



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

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

谢谢,

Ily*_*512 16

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

Post::find($post_id)->cats()->attach($cat_id);
Run Code Online (Sandbox Code Playgroud)

或者像这样附上多只猫:

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

如果你在变量中得到了Post模型对象,那么让我们说$ post:

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

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

如果您有一个类别作为模型对象,请说$ model:

$post->cats()->save($model);
Run Code Online (Sandbox Code Playgroud)

小心@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);
Run Code Online (Sandbox Code Playgroud)