刚刚在我的加入查询中遇到了一个错误。
我正在 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,因为这是代码中唯一不同的部分。
最佳答案
问题是您有多个名为 userid
的列。 followers.userid
和 blogs.userid
。现在,在这种情况下,不幸的是,当您使用 $build->userid
followers.userid
您只需选择
结果中所需的列即可更改此设置。
$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.*')
关于php - Laravel Join 返回奇数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27697779/