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
基础教程推荐
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- HTTP 与 FTP 上传 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01