Php Laravel 4:多对多(插入)
我在DB中有以下表格:Php Laravel 4:多对多(插入),php,mysql,laravel,laravel-4,Php,Mysql,Laravel,Laravel 4,我在DB中有以下表格: [posts, cats (categories), posts_cats (pivote)] posts表和cats之间的关系是多对多的 我在模型类中声明了关系: //Post.php public function cats() { return $this->belongsToMany('cats'); } //Cats.php public function post() { return $this->belongsToMan
[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');
}
问题是,如何插入多个类别的新帖子
谢谢,当您插入帖子时,请对类别进行评分并将其附加到新帖子上。诸如此类:
// $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);
}
我希望它能帮助你 来自文档
插入相关模型(多对多)
[…]您也可以使用同步方法附加相关模型。同步 方法接受要放置在透视表上的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
假设你知道帖子的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 = 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);
或者像这样连接多只猫:
Post::find($post_id)->cats()->attach($cat_id);
$cat_ids = array(1,2,3,4);
Post::find($post_id)->cats()->attach($cat_ids);
$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);
如果在变量中获得了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);
小心。这没有错,但是如果您想将类别添加到已经有类别的帖子中,那么应该使用attach()而不是sync()。Sync()将删除使用时未提供给它的所有其他内容
编辑:因此,如果您正在创建一个新的帖子,那么您可能正在执行以下操作:
Post::find($post_id)->cats()->attach($cat_id);
$cat_ids = array(1,2,3,4);
Post::find($post_id)->cats()->attach($cat_ids);
$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);
显示错误:“MassAssignmentException title”指$post=new post(数组('title'=>Input::get('title'),'topic'=>Input::get('topic'));这个,太多了!5.1文档链接:您的数据透视表应命名为:post_cat(单数vs复数)。您可以使用另一个透视表名称,但随后需要提供该表的名称作为BelongToMany()方法的第二个参数。如果我不知道post id(添加新post及其目录),该怎么办