Laravel / Eloquent : hasManyThrough WHERE(Laravel/Eloquent : hasManyThrough WHERE)
问题描述
在 Eloquent 的文档中,据说我可以将所需关系的键传递给 hasManyThrough.
In the documentation of Eloquent it is said that I can pass the keys of a desired relationship to hasManyThrough.
假设我有名为 Country、User、Post 的模型.通过用户模型,国家模型可能有许多帖子.也就是说,我可以直接调用:
Lets say I have Models named Country, User, Post. A Country model might have many Posts through a Users model. That said I simply could call:
$this->hasManyThrough('Post', 'User', 'country_id', 'user_id');
到目前为止一切正常!但是我如何才能只为 id 为 3 的用户获取这些帖子?
有人可以帮忙吗?
推荐答案
就这样:
models: Country
有很多 User
有很多 Post
models: Country
has many User
has many Post
这允许我们在您的问题中使用 hasManyThrough
:
This allows us to use hasManyThrough
like in your question:
// Country model
public function posts()
{
return $this->hasManyThrough('Post', 'User', 'country_id', 'user_id');
}
您想获取此关系的给定用户的帖子,因此:
You want to get posts of a given user for this relation, so:
$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 的用户的帖子时,它与国家无关)
BUT it will be easier, more readable and more eloquent if you use this instead: (since it has nothing to do with country when you are looking for the posts of user with 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
模型.
To sum up: hasManyThrough
is a way to get nested relation directly, ie. all the posts for given country, but rather not to search for specific through
model.
这篇关于Laravel/Eloquent : hasManyThrough WHERE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Laravel/Eloquent : hasManyThrough WHERE
- PHP - if 语句中的倒序 2021-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01