【问题标题】:Laravel hasManyThrough manipulates user_idLaravel hasManyThrough 操作 user_id
【发布时间】:2018-09-25 05:21:36
【问题描述】:

我遇到了 Laravel 中的 hasManyThrough 函数的问题。

我的目标是获取登录用户关注的用户显示帖子的提要。我尝试通过以下方式实现:

  1. 在User.php中,获取登录用户的ID
  2. 将用户的 id 与 Follow.php 中名为 user_id 的列匹配
  3. 从Follow.php的行中获取target_id
  4. 从 Follow.php 中获取 user_id 与 target_ids 匹配的帖子

我通过用户关注的人正确检索数据。但是,数据中返回的 user_id 是登录用户,而不是帖子的作者。为什么?

用户.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;

【问题讨论】:

    标签: php mysql laravel has-many-through


    【解决方案1】:

    您的代码创建此查询:select `posts`.*, `follows`.`user_id`...

    如您所见,posts.user_idfollows.user_id 覆盖(follows.user_id 是急切加载所必需的)。

    对于您的问题,我看到了两种可能的解决方案:

    1. 重命名follows.user_id
    2. 使用两个独立的关系:UserHasManyFollowHasManyPost

    【讨论】:

      猜你喜欢
      • 2018-07-22
      • 2014-09-19
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 2018-07-24
      • 2018-03-26
      • 1970-01-01
      • 2014-08-14
      相关资源
      最近更新 更多