2017-05-13 88 views
0

我有一个相应的表以下型号:与Laravel雄辩关系5.4

用户(用户),用户配置(user_profiles),评论(评论)

模式

table: users 

user_id (primary key) 
first_name 
last_name 

table: user_profiles 
user_id (foreign key) 
country 
phone 

table: reviews 
reviewer_id (the user who posted the review) 
user_id (foreign key) 
body 

我用以下查询数据库:

$user = User::with('profile', 'review')->find(Auth::User()->user_id); 
用户模型3210

部分

public function profile(){ 
    return $this->hasOne(UserProfile::class, 'user_id'); 
}  

public function review(){ 
    return $this->hasOne(Review::class, 'user_id'); 
} 

用户配置的零件模型评论部分的

public function users() { 
    return $this->belongsTo(User::class, 'user_id'); 
} 

型号

public function users() { 
    return $this->belongsTo(User::class, 'user_id'); 
} 

我怎样才能访问reviewer的细节使用reviewer_id from users

+0

你们的关系是不是一个多对多的,这是一个多对一。用户应该'$ this-> haveMany()'和UserProfile应该'$ this-> belongsTo()' –

+0

你的问题混淆了'reviewer_id'和'user_id'之间的区别。看起来他们是一回事。 –

+0

'reviewer_id'实际上持有'user_id'数据,但对于撰写评论的用户 – BlackPearl

回答

2

作为这个问题中讨论过的sunup,我认为OP的主要关注点是关于一个表有两个外键具有相同的表。 user_idreviewer_id都是连接到users表的外键。

了解Laravel关系的一个重要的事情是,关系名称不是硬性限制,只要它对您有意义,它可以是任何东西。相关对象将在ATTRIBUTE中可用,其确切名称为METHOD

class User extends Model { 

    public function review() { 
     return $this->hasOne(Review::class); 
    } 
} 

用户的审核将可在User::find(1)->review;

class Review extends Model { 

    public function owner() { 
     return $this->belongsTo(User::class, 'user_id'); 
    } 

    public function reviewer() { 
     return $this->belongsTo(User::class, 'reviewer_id');  
    } 
} 

从审核,您将能够同时访问用户:

Review::find(1)->owner; // This is the relationship with user_id column 
Review::find(1)->reviewer; // This is the relationship with reviewer_id column