Laravel hasManyThrough 操作 user_id
Laravel hasManyThrough manipulates user_id
我在 Laravel 中的 hasManyThrough 函数遇到问题。
我的目标是获得一个提要,其中 post 由登录用户关注的用户显示。我尝试通过以下方式实现这一目标:
- 在User.php中获取登录用户的ID
- 将用户的 ID 与 Follow.php
中名为 user_id 的列相匹配
- 从 Follow.php
中的行中获取 target_id
- 获取 posts,其中 user_id 匹配来自 Follow.php
的 target_ids
我通过用户关注的人正确检索了数据。但是,数据中返回的 user_id 是登录用户,而不是 post 的作者。为什么?
User.php
public function feed() {
return $this->hasManyThrough(
'App\Post',
'App\Follow',
'user_id',
'user_id',
'id',
'target_id'
)
->with('user')
->orderBy('id', 'DESC');
}
Post.php
public function user() {
return $this->belongsTo('App\User');
}
通过
从控制器调用
$posts = Auth::user()->feed;
您的代码创建了这个查询:select `posts`.*, `follows`.`user_id`...
如您所见,posts.user_id
被 follows.user_id
覆盖(follows.user_id
是预先加载所必需的)。
我看到两个可能的解决方案来解决您的问题:
- 重命名
follows.user_id
.
- 使用两个独立的关系:
User
→ HasMany
→ Follow
→ HasMany
→ Post
我在 Laravel 中的 hasManyThrough 函数遇到问题。
我的目标是获得一个提要,其中 post 由登录用户关注的用户显示。我尝试通过以下方式实现这一目标:
- 在User.php中获取登录用户的ID
- 将用户的 ID 与 Follow.php 中名为 user_id 的列相匹配
- 从 Follow.php 中的行中获取 target_id
- 获取 posts,其中 user_id 匹配来自 Follow.php 的 target_ids
我通过用户关注的人正确检索了数据。但是,数据中返回的 user_id 是登录用户,而不是 post 的作者。为什么?
User.php
public function feed() {
return $this->hasManyThrough(
'App\Post',
'App\Follow',
'user_id',
'user_id',
'id',
'target_id'
)
->with('user')
->orderBy('id', 'DESC');
}
Post.php
public function user() {
return $this->belongsTo('App\User');
}
通过
从控制器调用$posts = Auth::user()->feed;
您的代码创建了这个查询:select `posts`.*, `follows`.`user_id`...
如您所见,posts.user_id
被 follows.user_id
覆盖(follows.user_id
是预先加载所必需的)。
我看到两个可能的解决方案来解决您的问题:
- 重命名
follows.user_id
. - 使用两个独立的关系:
User
→HasMany
→Follow
→HasMany
→Post