php - 拉维尔 4 : many to many (insertion)

标签 php mysql laravel laravel-4

我在数据库中有这些表:

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

posts表和cat之间的关系是多对多

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

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



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

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

谢谢,

最佳答案

假设您知道帖子的 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);

关于php - 拉维尔 4 : many to many (insertion),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23908040/

相关文章:

mysql - 如何在左外连接上使用 laravel 中的 select 作为第二个条件

php - 如何在mysql中插入阿拉伯字母

php - 如何在 EC2 上启动 Apache

php - SQL - 搜索表单中的多个表

mysql - 停止在 tz 更改时自动更改 MySQL 中的日期

php - Laravel:自定义 http 状态代码不起作用

php - SQL查找表中的特定字符

mysql - Spring Boot Jdbc Flyway 版本文件名 "V1__script.sql"不起作用,而是使用 "V1_file.sql"重命名文件正在起作用

mysql - Liquibase mysql 存储换行符

php - 如何将上传的文件以给定的名称存储在磁盘上?