Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent pivot table with different column name

Tags:

php

eloquent

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

like image 284
handsome Avatar asked Jun 10 '19 04:06

handsome


1 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();
like image 124
Dhananjay Kyada Avatar answered Oct 26 '22 23:10

Dhananjay Kyada