提问者:小点点

雄辩的hasManyThrough也能获得中间表信息


我有相同的表结构,在laravel文档中提到的HasManyBy关系hasManyBy

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

以上仅返回发布数据。.


共2个答案

匿名用户

您需要的是在帖子旁边加载用户,这可以通过生成器上的with()方法实现:

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

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

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

然后您可以简单地使用$post-

有关更多信息,请参阅文档。

匿名用户

试试这个:

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