我在数据库中有这些表:
[posts, cats (categories), posts_cats (pivote)]posts表和猫之间是多对多的关系
我在models类中声明了关系:
//Post.php
public function cats()
{
return $this->belongsToMany('cats');
}
//Cats.php
public function post()
{
return $this->belongsToMany('posts');
}问题是,如何插入具有多个类别的新帖子?
谢谢,
发布于 2014-05-28 19:06:46
假设你知道帖子的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);发布于 2014-05-28 18:03:07
当您插入帖子时,然后遍历类别并将它们附加到新帖子。大概是这样的:
// $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);
}我希望它能对你有所帮助。
发布于 2014-05-28 18:03:26
从docs http://laravel.com/docs/eloquent#inserting-related-models
插入相关模型(多对多)
..。也可以使用sync方法附着相关模型。sync方法接受要放在数据透视表上的ID数组。此操作完成后,只有数组中的is将位于模型的中间表中:
和一个代码示例:
$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 $categoryIdshttps://stackoverflow.com/questions/23908040
复制相似问题