Eloquent pivot table with different column name

Viewed 491

Users table

- id
- name (string)

Visits table

- id
- user_id
- viewer_id 

I want to get a list of visits with the linked username for a given user (in this case id = 1)

$visits = \Visits::where(['user_id' => 1])->with('user')->get();

this is my visits model:

class Visits extends Model
{

    protected $table = 'visits';

    public function store(Request $request)
    {
        $visits = new Visits;
        $visits->save();
    }

    public function user()
    {
        return $this->belongsTo('User', 'viewer_id');
    }

}

this is my User model

use Illuminate\Database\Eloquent\Model;

class User extends Model
{

    public function store(Request $request)
    {
        $user = new User;
        $user->save();
    }

}

it returns the data but the "user" is null

2 Answers

I think you need to change your code a little bit. Please try the following:

public function user()
{
    return $this->belongsTo('App\User', 'viewer_id', 'id');
}

$visits = \Visits::where(['user_id' => 1])->with('user')->get();

I am assuming, in your visits table, user_id is the person who has been visited and viewer_id are the persons/users who have visited.

So, my Visits model would have been something like this

class Visits extends Model
{
    protected $table = 'visits';
    protected $fillable = array('user_id','viewer_id'); //Fillable is for Mass Assignment


    public function user()
    {
        return $this->belongsTo(User::class,'user_id','id');
    }

   public function visitorsDetails(){
     return $this->belongsTo(User::class,'viewer_id','id');
   }   
}

Now for getting all the visitors detail for user with user_id=1, I would do something like this.

$visitorList = Visits::where('user_id',1)->with('visitorsDetails')->get();
echo <pre>;
print_r($visitorList->toArray()); // This will show the visitor with visitors detail in an array form.

Note: I am not sure why you are writing store function inside modal, it is not required you can directly save data from the controller itself.

Related