2

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 e.g.:

$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.

1 Answer 1

3

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 selecting 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

Sign up to request clarification or add additional context in comments.

4 Comments

I went through that a second ago as I had the same idea, but doesn't appear to sort it. Ill try to narrow the problem some more.
Ah I think I know why. Do you have different userid columns in your db?
Interesting thought. And yes I do. In the blogs table I also have a userid field... store store the userid. Looks like Ill have to change it and try :)
I rewrote my answer. Take a look at it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.