【问题标题】:Laravel / Eloquent : hasManyThrough WHERELaravel / Eloquent : hasManyThrough WHERE
【发布时间】:2014-08-14 20:05:17
【问题描述】:

在 Eloquent 的文档中,据说我可以将所需关系的密钥传递给 hasManyThrough。

假设我有名为 Country、User、Post 的模型。 Country 模型可能通过 Users 模型有许多 Posts。那就是说我可以打电话:

$this->hasManyThrough('Post', 'User', 'country_id', 'user_id');

到目前为止还不错! 但我怎样才能只为 id 为 3 的用户获取这些帖子?

有人可以帮忙吗?

【问题讨论】:

  • 在User 模型上设置关系并为您想要的用户获取帖子。或者使用has 方法查询关系。或使用查询生成器.. 提出精确的问题以获得准确的答案
  • 老实说,您的所有建议听起来都很有趣。我只是在寻找一种方法来实现这一点,不知道如何更准确地问=(

标签: php laravel relational-database eloquent


【解决方案1】:

就这样吧:

型号:Country 有很多 User 有很多 Post

这允许我们在您的问题中使用hasManyThrough:

// Country model
public function posts()
{
  return $this->hasManyThrough('Post', 'User', 'country_id', 'user_id');
}

您想获取给定用户的此关系的帖子,所以:

$country = Country::first();
$country->load(['posts' => function ($q) {
  $q->where('user_id', '=', 3);
}]);
// or
$country->load(['posts' => function ($q) {
  $q->has('user', function ($q) {
    $q->where('users.id', '=', 3);
  });
})

$country->posts; // collection of posts related to user with id 3

但是如果你改用它会更容易,更易读,更雄辩: (因为在查找 id 为 3 的用户的帖子时,它与国家无关)

// User model
public function posts()
{
  return $this->hasMany('Post');
}

// then
$user = User::find(3);
// lazy load
$user->load('posts');
// or use dynamic property
$user->posts; // it will load the posts automatically
// or eager load
$user = User::with('posts')->find(3);

$user->posts; // collection of posts for given user

总结一下:hasManyThrough 是一种直接获取嵌套关系的方法,即。给定国家/地区的所有帖子,而不是搜索特定的through 模型。

【讨论】:

  • 非常感谢!顺便说一句:该示例取自雄辩的文档站点。我完全同意你的看法!
【解决方案2】:
$user_id = 3;

$country = Country::find($country_id);

$country->posts()->where('users.id', '=', $user_id)->get();

【讨论】:

    【解决方案3】:

    $this->hasManyThrough('Post', 'User', 'country_id', 'user_id')->where(column,x);

    这里发生的事情是你得到集合作为回报,你可以在最后放置任何你想要的条件。

    【讨论】:

      猜你喜欢
      • 2020-03-07
      • 2016-09-24
      • 2020-10-14
      • 2016-08-21
      • 2016-09-26
      • 2019-03-26
      • 2015-07-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多