【发布时间】:2016-10-13 10:35:39
【问题描述】:
我有 3 个表 posts、tags 和一个数据透视表 post_tag。
post_tag 表是:
+----+-------------+--------+
| id | post_id | tag_id |
+----+-------------+--------+
| 1 | 1 | 2 |
| 2 | 2 | 2 |
| 3 | 3 | 1 |
| 4 | 4 | 1 |
| 5 | 4 | 3 |
| 6 | 5 | 3 |
+----+-------------+--------+
我在Post 模型中有这个:
class Post extends Model {
public function tags() {
return $this->belongsToMany('Tag');
}
}
这在Tag 模型中:
class Tag extends Model {
public function posts() {
return $this->belongsToMany('Post');
}
}
现在在我的控制器中,我试图将记录插入数据透视表post_tag:
$post = Post::find(4);
$post_tag = $post->tags()->attach(2);
return $post_tag //it returns null
所以,我需要在数据透视表中获取已创建记录的详细信息,但 $post_tag 包含 null!
如何获取数据透视表上最后插入记录的详细信息(如 id ,...)?
【问题讨论】:
标签: php mysql laravel eloquent laravel-5.2