php – Laravel雄辩的嵌套关系仅在第一个元素上返回数据

前端之家收集整理的这篇文章主要介绍了php – Laravel雄辩的嵌套关系仅在第一个元素上返回数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
介绍

我有一些困扰得到所有相关元素的数据. Im使用Laravel作为REST后端服务,将Json暴露给前端JavaScript应用程序.

数据结构

考虑我有以下表格:

  1. +----------------+ +----------------+ +-------------+
  2. |topics | |posts | |users |
  3. +----------------+ +----------------+ +-------------+
  4. |id: int | |id: int | |id: int |
  5. |title: varchar | |content: varchar| |name: varchar|
  6. |content: varchar| |user_id: int | +-------------+
  7. |user_id: int | |topic_id: int |
  8. +----------------+ +----------------+

一个主题有0到多个帖子,它有一个作者(用户)

一个帖子有一个作者(用户)

UML:http://i58.servimg.com/u/f58/11/26/57/95/intrep10.png

Laravel模型

  1. class User extends Eloquent {
  2. protected $table = 'users';
  3.  
  4. public function topics() {
  5. reutrn $this->hasMany('Topic');
  6. }
  7.  
  8. public function posts() {
  9. reutrn $this->hasMany('Post');
  10. }
  11. }
  12.  
  13. class Topic extends Eloquent {
  14. protected $table = 'topics';
  15.  
  16. public function posts() {
  17. return $this->hasMany('Post');
  18. }
  19.  
  20. public function author() {
  21. return $this->hasOne('User','id');
  22. }
  23. }
  24.  
  25. class Post extends Eloquent {
  26. protected $table = 'posts';
  27.  
  28. public function topic() {
  29. return $this->belongsTo('Topic');
  30. }
  31.  
  32. public function author() {
  33. return $this->hasOne('User','id');
  34. }
  35. }

调节器

  1. return Topic::where('id','=',$topicId)
  2. ->with('author','posts.author')
  3. ->get();

产量

  1. [{
  2. 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: {
  3. id: 1,name: "JamesBond",},posts: [{
  4. id: 1,content: "Reply 1 on topic 1",author: {
  5. id: 1,{
  6. id: 2,content: "Reply 2 on topic 1",author: null,}]
  7. }]

正如你可以看到jsoncode,这两个帖子都是由同一个用户(id 1)创建的,但只有第一个具有作者对象.
任何关于如何弄清楚我的问题的指针都将是完美的.

放弃

这是我的项目的条纹化版本,因为我不想用信息垃圾邮件.如果我没有这个问题的服务元素,我会很乐意提供.

我的模型映射已经关闭了.

  1. public function author() {
  2. return $this->belongsTo('User','user_id','id');
  3. }

确保其在user表中查找的user_id与用户表中的id列相对应

  1. SELECT * FROM users WHERE id = posts.user_id;
在你的主题模型中,作者的关系应该是
  1. class Topic extends Eloquent {
  2.  
  3. //...
  4.  
  5. public function author() {
  6. return $this->belongsTo('User');
  7. }
  8. }

同样的你的邮政模型:

  1. class Post extends Eloquent {
  2.  
  3. // ...
  4.  
  5. public function author() {
  6. return $this->belongsTo('User');
  7. }
  8. }

这是因为在两个表格主题和帖子中都有user_id,user_id与users表相关联,所以,以这种方式,您的主题和帖子表中的每个user_id都属于users表,其中users表中的对应字段是id.在这种情况下,主题和帖子表都是用户表的小孩.

猜你在找的Laravel相关文章