Laravel加入返回奇数值

时间:2014-12-29 23:58:53

标签: php mysql join laravel

刚刚遇到我的加入查询的错误。

我在foreach中回显数据,并显示用户名。在其他页面上,它工作正常,每个用户名都匹配行中ID的用户名。但是,在下面的示例中,用户名返回始终是登录用户的名称。

希望下面的内容更有意义。感谢。

查询是:

$query = DB::table('blogs')
  ->join('followers', 'blogs.id', '=', 'followers.blogid')
  ->where('followers.userid', Auth::user()->id)
  ->where('frontpage', '1')
  ->latest('lastupdated');

通过以下方式调用:

Route::get('following', array('before' => 'auth', function()
{
  $slug = Route::getCurrentRoute()->uri();
  $builds = Blog::findBuilds($slug);
  return View::make('pages/home', compact('builds'), array('pageTitle' => 'Builds You Are Following'));
}));

然后在页面/主页上,我正在显示数据:

foreach ($builds as $build)
{
  $usernameOfOwner = User::usernameFromID($build->userid);
}

然后......从ID获取用户名的功能是:

public static function usernameFromID($id) {
  $user = DB::table('users')->where('id', $id)->first();
  return $user->username;
}

当我运行类似于顶层但不是连接的查询时,我网站上的其他任何地方,例如:

$query = static::where('frontpage', '1')->latest('lastupdated');

它工作正常,所以我唯一的猜测是它归结为Join,因为这是代码中唯一不同的部分。

1 个答案:

答案 0 :(得分:3)

问题是您有多个名为userid的列。 followers.useridblogs.userid。现在,在这种情况下,当您使用followers.userid

时,很遗憾会返回$build->userid

您只能select在结果中添加所需的列。

$userid = Auth::user()->id;
$query = DB::table('blogs')
  ->join('followers', function($q) use ($userid){
      $q->on('blogs.id', '=', 'followers.blogid');
      $q->where('followers.userid', '=', $userid);
  })
  ->select('blogs.userid', 'other-column')
  ->where('frontpage', '1')
  ->latest('lastupdated');

顺便说一句:*也有效,所以如果你愿意,你可以select('blogs.*')