【发布时间】:2014-04-09 11:35:09
【问题描述】:
简介
我在获取所有相关元素的数据时遇到了一些麻烦。我使用 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 |
+----------------+ +----------------+
一个主题有 0 到多个帖子,并且它有一个作者(用户)
一篇文章有一个作者(用户)
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",
created_at: "2014-03-06",
updated_at: "2014-03-06",
},
posts: [{
id: 1,
content: "Reply 1 on topic 1",
user_id: 1,
created_at: "2014-03-06",
updated_at: "2014-03-06",
author: {
id: 1,
name: "JamesBond",
created_at: "2014-03-06",
updated_at: "2014-03-06",
},
},
{
id: 2,
content: "Reply 2 on topic 1",
user_id: 1,
created_at: "2014-03-06",
updated_at: "2014-03-06",
author: null,
}]
}]
问题
正如您在 jsoncode 中看到的,两个帖子都是由同一个用户(ID 为 1)创建的,但只有第一个帖子上有作者对象。 任何关于如何找出我的问题的指示都是完美的。
免责声明
这是我项目的精简版,因为我不想用信息向问题发送垃圾邮件。如果我的问题缺少明确的元素,我很乐意提供。
解决方案
我的模型映射已关闭。
public function author() {
return $this->belongsTo('User', 'user_id', 'id');
}
确保它在帖子表中查找的 user_id 与用户表中的 id 列相对应
SELECT * FROM users WHERE id = posts.user_id;
【问题讨论】:
标签: php laravel entity-relationship eloquent eager-loading