R. *_*sen 12 php entity-relationship eager-loading laravel eloquent
我正在努力获取所有相关元素的数据.我使用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 |
+----------------+ +----------------+
Run Code Online (Sandbox Code Playgroud)
一个主题有0到多个帖子,它有一个作者(用户)
帖子有一位作者(用户)
UML:http://i58.servimg.com/u/f58/11/26/57/95/intrep10.png
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');
}
}
Run Code Online (Sandbox Code Playgroud)
return Topic::where('id', '=', $topicId)
->with('author', 'posts.author')
->get();
Run Code Online (Sandbox Code Playgroud)
[{
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,
}]
}]
Run Code Online (Sandbox Code Playgroud)
正如您所看到的jsoncode,这两个帖子都是由同一个用户创建的(ID为1),但只有第一个帖子上有作者对象.关于如何找出问题的任何指示都是完美的.
这是我的项目的条纹版本,因为我不想用信息垃圾邮件.如果我缺少这个问题的元素,我会很乐意提供它.
我的模型映射已关闭.
public function author() {
return $this->belongsTo('User', 'user_id', 'id');
}
Run Code Online (Sandbox Code Playgroud)
确保它在posts表中查找的user_id,与users表中的id列相对应
SELECT * FROM users WHERE id = posts.user_id;
Run Code Online (Sandbox Code Playgroud)
在您的Topic模型中, 的关系author应该是
class Topic extends Eloquent {
//...
public function author() {
return $this->belongsTo('User');
}
}
Run Code Online (Sandbox Code Playgroud)
您的模型也是如此Post:
class Post extends Eloquent {
// ...
public function author() {
return $this->belongsTo('User');
}
}
Run Code Online (Sandbox Code Playgroud)
这是因为,在两个表中topics,posts您都有user_id和 与user_id表相关users,所以,这样想,user_id您topics和posts表中的每个都属于user表,相应的字段在表id中users。在这种情况下, 和topics表posts都是users表的子项。
| 归档时间: |
|
| 查看次数: |
6345 次 |
| 最近记录: |