简体   繁体   中英

Laravel Join Returning odd values

Just come across a bug on my Join query.

I am echoing out data in a foreach, and showing the username. On other pages it works fine and each username matches the username from the ID in the row. However, in the example below the username return is ALWAYS the name of the logged in user.

Hope the below makes some more sense. Thanks.

The query is:

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

This is called via:

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'));
}));

And then on the pages/home I am showing the data like so:

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

And then... the function for getting the username from ID is:

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

Everywhere else on my website when I run a query similiar to the top one but not a join so eg:

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

It works fine, so my only guess is that its down to the Join as thats the only different part of the code.

The problem is that you have multiple columns named userid . followers.userid and blogs.userid . Now in this case, unfortunately followers.userid gets returned when you use $build->userid

You can change that by only select ing the columns you want in your result.

$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');

By the way: * works too, so you can do select('blogs.*') if you want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM