I am trying to join two tabels using Laravel (just started using it). One table holds user information, and the other table holds a users friend IDs.
So one user can have multiple friends. I have done this is the user class:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table="user_info";
public function getFriends()
{
//user_id is the column in the user_friends table that should be linked to the id table in this class table (user_info)
return $this->hasMany('App\UserFriends','user_id','id');
}
}
And the other class (UserFriends)
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserFriends extends Model
{
protected $table="user_friends";
}
Then in a controller I call
$t = $this->sql_obj->getFriends()->toSql();
However, if I print the result of this it returns this:
select * from `user_friends` where `user_friends`.`user_id` is null and `user_friends`.`user_id` is not null
Why is it not joining the tables?
Thanks for any help!
in Your UserModel :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table="user_info";
public function getFriends()
{
return $this->belongsToMany('App\User', 'user_friends', 'user_id', 'id');
}
}
in your controller :
if you want to get Auth user's friend :
public function friends(Request $request){
$friends = Auth::user()->getFriends;
return response()->json(array('friends'=>$friends));
}
if you want to get other user's friends :
public function friends(Request $request){
$userid=$request->input('userid');
$user=User::find($userid);
$friends = $user->getFriends;
return response()->json(array('friends'=>$friends));
}
or If you want to use query builder to join :
use DB;
public function friends(Request $request){
$userid=$request->input('userid'); // Auth::user()->id
$friends= DB::table('user_info')
->join('user_friends', 'user_info.id', '=', 'user_friends.user_id')
->where('user_friends.user_id', '=',$userid)
->select('user_info.*')
->get();
return response()->json(array('friends'=>$friends));
}