【问题标题】:Laravel eloquent Has Many Through relationshipLaravel 雄辩有很多通过关系
【发布时间】:2018-07-07 04:44:11
【问题描述】:

所以,就是这样。我有 3 个表,它们的结构如下:

**user**
 -id
 -name
 -password
 -etc...

**user_general_info**
 -id
 -the_user_id
 -country_id
 -phone
 -desc
 ...

**country**
 -id
 -name

出于显而易见的原因,我为它们中的每 3 个设置了模型。现在我如何声明这三个之间的雄辩关系,以便我可以获得用户国家的数据(类似于$user->user_general_info->user_country->name)。?我已经尝试了hasManyThrough,但没有成功。

我必须将country 外键 添加到user 表吗?还是我错过了什么?

提前致谢。

【问题讨论】:

  • 一个用户可以在user_general_info中有多个条目吗?
  • 没有。用户在user_general_info 表中只能有 1 个条目。
  • 如果用户可以有多个条目,BelongsToMany 关系将是最佳选择。

标签: php laravel eloquent relational-database


【解决方案1】:

有多种方法可以处理此问题。但是,最简洁的方法之一是在用户模型中声明 hasOne 关系并检索结果。

所以假设你有三个模型,UserUserGeneralInfoCountry。转到您的 User 模型并声明以下内容。

 public function userGeneralInfo()
 {
     return $this->hasOne('App\UserGeneralInfo', 'user_id', 'id');
 }


 public function userCountry()
 {
     return $this->hasOne('App\Country', 'user_id', 'id');
 }

现在查询时使用以下内容

$user = User:where('id, $id)->with('userGeneralInfo')->with('userCountry')->first();

这将为您提供用户及其相关的一般信息和用户国家/地区。现在您可以使用访问变量了。

$user->userGeneralInfo->phone 检索电话号码。同样,$user-> userCountry->name 获取国家名称。

注意:有多种方法可以获得您想要的结果,这是一种最简单的方法,让初学者能够理解。您可以了解更多关于复杂关系laravel relationships

【讨论】:

  • 反比关系呢?我的意思是country 可以有很多user。我怎样才能在country 中获得所有user?但只有user_general_info 有这两个外键。
猜你喜欢
  • 1970-01-01
  • 2017-08-03
  • 2015-11-01
  • 2020-04-10
  • 1970-01-01
  • 1970-01-01
  • 2020-06-30
  • 1970-01-01
  • 2012-10-08
相关资源
最近更新 更多