【发布时间】:2013-06-03 06:16:44
【问题描述】:
我想知道如何从 3 个表创建关系。
这是我的模型结构:
用户模型
class User extends Eloquent {
public function Posts(){
return $this->hasMany('Post');
}
public function comments(){
return $this->hasMany('comment');
}
}
class Post extends Eloquent {
public function comments() {
return $this->hasMany('Comments');
}
public function user(){
return $this->belongsTo('user');
}
}
class Comments extends Eloquent {
public function user(){
return $this->belongsTo('user');
}
public function Post(){
return $this->belongsTo('Post');
}
}
用户可以有很多帖子,每个帖子都有很多来自用户的cmet。
我试图从发布评论的用户的帖子中获取所有 cmets
$comments = Post::find(1)->comments()->get();
foreach ($comments as $comment) {
// here my code now to get the user
$comment->user()->get()
}
结果:
[
{
id: "1",
post_id: "1",
user_id: "1",
reply_text: "Testing",
},...
]
我认为它根本没有效率。
我怎样才能让这个更简单:
[
{
id: "1",
post_id: "1",
user_id: "1",
reply_text: "Testing",
user_post: {
id: 1,
name: "Edi vianika",
profil_img: "l.jpg"
}
}
]
【问题讨论】:
-
查看文档中关于Eager Loading 的部分,看看它是否回答了您的任何问题。您不需要将
$comment->user()->get()用于关系。 -
谢谢@PhillSparks .. 这对我有用
return Tweet::with('user')->get();真的很有帮助。