2014-12-04 154 views
0

很多搜​​索我无法找到一个真正解决我的“问题”后,如果有任何一个人如何能帮助我,我'一切听hasManyThrough关系的雄辩laravel 4

...

我有树模型,邮政,用户和简介

Post belongsTo user – user hasMany posts == One –to-Many relation 
Profile belongsTo user – user hasOne profile == One-to-One relation 

数据库结构

User 

---- id : primary key 
---- email : string 
---- name : string 

...

Profile 

---- id : primary key 
---- user_id : foreign key 
---- biography : text 
---- facebook : strings 

...

Post 

---- id : primary key 
---- user_id : foreign key 
---- title : string 
---- slug : string 
---- body : text 

...

用户模型

class User extends Eloquent { 
    public function posts(){ 
     return $this->hasMany('Post'); 
    } 
    public function profile(){ 
     return $this->hasOne('Profile'); 
    } 
} 

剖面模型

class Profile extends \Eloquent { 
    public function user(){ 
     return $this->hasOne('User'); 
    } 
} 

Post模型

class Post extends \Eloquent { 
    public function user(){ 
     return $this->belongsTo('User'); 
    } 
} 

如何我可以通过帖子

我希望我很清楚的得到配置文件表中的用户个人简历(或任何其他属性)

回答

0

有中没有hasManyThrough你建立。

首先修复这种关系:

//Profile  
public function user(){ 
    return $this->belongsTo('User'); 
} 

然后简单:

$post->user->profile->biography; 

$user->profile->biography; 

有过帖子没有规范的数据,因为这两个postprofile属于用户。


还有另一种方式来链接postsprofiles表:

// Post model 
public function profile() 
{ 
    return $this->hasOne('Profile', 'user_id', 'user_id'); 
} 

// Profile model 
public function posts() 
{ 
    return $this->hasMany('Post', 'user_id', 'user_id'); 
} 

然后:

$post->profile->biography; 

$profile->posts; // collection of Post models 

这样你通过不取的User模式保存一个查询。

+0

谢谢@Jarek我明白了:-) – chebaby 2014-12-08 21:55:57