【问题标题】:Eloquent Relationship with Laravel 5.4与 Laravel 5.4 的雄辩关系
【发布时间】:2017-10-12 23:16:22
【问题描述】:

我有以下模型和相应的表格:

用户(users)、UserProfile(user_profiles)、评论(reviews)

架构

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);

部分用户模型

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

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

UserProfile 模型的一部分

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

部分评审模型

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

如何使用users 表中的reviewer_id 访问reviewer 的详细信息

【问题讨论】:

  • 你们的关系不是多对多,而是多对一。用户应该 $this->haveMany() 和 UserProfile 应该 $this->belongsTo()
  • 您的问题令人困惑,reviewer_iduser_id 之间的区别是什么。看起来它们是一样的。
  • reviewer_id 实际上持有 user_id 数据,但对于撰写评论的用户而言
  • 在 Review Model 中,您应该有一种方法用于 user() 和 belongsTo User 和 user_id 和一种方法 reviewer() 和 belongsTo User 和 reviewer_id。然后,从你的 $user 变量做 $user->review->reviewer 应该给你用户通过 reviewer_id
  • @MarcoAurélioDeleu 谢谢,按要求工作

标签: laravel-5


【解决方案1】:

作为这个问题中讨论的内容的补充,我认为 OP 的主要关注点是关于一个表,该表具有同一个表的 2 个外键。 user_idreviewer_id 都是链接到 users 表的外键。

了解 Laravel 关系的重要一点是,关系名称不是硬绑定的,只要对您有意义,它可以是任何名称。相关对象将以 METHOD 的确切名称在 ATTRIBUTE 中提供。

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

【讨论】:

    猜你喜欢
    • 2017-10-01
    • 1970-01-01
    • 2018-01-11
    • 2017-05-19
    • 2017-10-04
    • 1970-01-01
    • 2017-04-14
    • 2015-03-14
    • 2018-11-28
    相关资源
    最近更新 更多