介绍
我有一些困扰得到所有相关元素的数据. Im使用Laravel作为REST后端服务,将Json暴露给前端JavaScript应用程序.
数据结构
考虑我有以下表格:
- +----------------+ +----------------+ +-------------+
- |topics | |posts | |users |
- +----------------+ +----------------+ +-------------+
- |id: int | |id: int | |id: int |
- |title: varchar | |content: varchar| |name: varchar|
- |content: varchar| |user_id: int | +-------------+
- |user_id: int | |topic_id: int |
- +----------------+ +----------------+
一个帖子有一个作者(用户)
UML:http://i58.servimg.com/u/f58/11/26/57/95/intrep10.png
Laravel模型
- class User extends Eloquent {
- protected $table = 'users';
- public function topics() {
- reutrn $this->hasMany('Topic');
- }
- public function posts() {
- reutrn $this->hasMany('Post');
- }
- }
- class Topic extends Eloquent {
- protected $table = 'topics';
- public function posts() {
- return $this->hasMany('Post');
- }
- public function author() {
- return $this->hasOne('User','id');
- }
- }
- class Post extends Eloquent {
- protected $table = 'posts';
- public function topic() {
- return $this->belongsTo('Topic');
- }
- public function author() {
- return $this->hasOne('User','id');
- }
- }
调节器
- return Topic::where('id','=',$topicId)
- ->with('author','posts.author')
- ->get();
产量
- [{
- id: 1,title: "My Topic",content: "With opinions about the darkside",user_id: 1,created_at: "2014-03-06",updated_at: "2014-03-06",author: {
- id: 1,name: "JamesBond",},posts: [{
- id: 1,content: "Reply 1 on topic 1",author: {
- id: 1,{
- id: 2,content: "Reply 2 on topic 1",author: null,}]
- }]
题
正如你可以看到jsoncode,这两个帖子都是由同一个用户(id 1)创建的,但只有第一个具有作者对象.
任何关于如何弄清楚我的问题的指针都将是完美的.
放弃
这是我的项目的条纹化版本,因为我不想用信息垃圾邮件.如果我没有这个问题的服务元素,我会很乐意提供.
解
我的模型映射已经关闭了.
- public function author() {
- return $this->belongsTo('User','user_id','id');
- }
确保其在user表中查找的user_id与用户表中的id列相对应
- SELECT * FROM users WHERE id = posts.user_id;
在你的主题模型中,作者的关系应该是
- class Topic extends Eloquent {
- //...
- public function author() {
- return $this->belongsTo('User');
- }
- }
同样的你的邮政模型:
- class Post extends Eloquent {
- // ...
- public function author() {
- return $this->belongsTo('User');
- }
- }
这是因为在两个表格主题和帖子中都有user_id,user_id与users表相关联,所以,以这种方式,您的主题和帖子表中的每个user_id都属于users表,其中users表中的对应字段是id.在这种情况下,主题和帖子表都是用户表的小孩.