我想知道如何从 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');
}
}
用户可以有很多帖子,每个帖子都有很多来自用户的评论。
我试图从发布评论的用户那里获取所有评论
$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"
}
}
]