【问题标题】:Eloquent hasManyThrough also get middle table informationEloquent hasManyThrough 也获取中间表信息
【发布时间】:2019-10-04 11:34:04
【问题描述】:

我的表结构与 laravel 文档中提到的 HasManyThrough 关系 hasManyThrough 中的表结构相同

countries
  id - integer
  name - string 

users
  id - integer
  country_id - integer
  name - string

posts
  id - integer
  user_id - integer
  title - string

并定义与文档中相同的关系。

public function posts()
{
    return $this->hasManyThrough(
        'App\Post', 'App\User',
        'country_id', 'user_id', 'id'
    );
}

现在当我列出特定国家的帖子时。我也需要帖子用户的信息。我的意思是来自数据透视表(用户)的信息

$posts = Country::find(2)->posts();

以上仅返回帖子数据..

【问题讨论】:

    标签: laravel relationship has-many-through


    【解决方案1】:

    试试这个:

    $posts = Country::find(2)->posts()->with('user')->get();
    

    【讨论】:

      【解决方案2】:

      您需要在帖子旁边预先加载用户,可以通过 Builder 上的 with() 方法实现:

      $posts = Country::find(2)->posts()->with('user')->get();
      

      如果您要加载大量数据并且不想加载整个 User 实例,您甚至可以指定仅从 users 表中检索哪些字段:

      $posts = Country::find(2)->posts()->with('user:id,name')->get();
      

      然后您可以简单地使用$post->user->name 或迭代您的集合时需要的任何内容。

      有关更多信息,请参阅documentation

      【讨论】:

      • 对于急切加载,我需要定义帖子和用户权限之间的关系...?或者它将与我当前定义的 hasManyThrough 关系一起使用?
      • 您必须在Post 模型中定义关系,但我认为这是值得的。您以后可能还需要这种关系,它不会过时,因为它无论如何都存在。 :)
      • 谢谢...它的工作..我只是坚持使用 hasManyThrough 关系来寻找出路。并没有考虑其他关系拍照..
      • 需要更多帮助。这给了我错误。 Country::find(2)->posts()->with('user:id,name')->get(); insted of id 我的列名是 id_user
      • 这只是一个示例,当然,如果与您的列名匹配,您必须将id 更改为user_id
      猜你喜欢
      • 2015-12-09
      • 1970-01-01
      • 2013-09-05
      • 2014-08-14
      • 2020-03-07
      • 2016-09-24
      • 2015-07-13
      • 2020-10-14
      • 1970-01-01
      相关资源
      最近更新 更多