Ronon
Ronon

Reputation: 842

laravel eloquent belongsTo fetches wrong data

I have two tables. One contains the user and the other contains meetings. Each meeting belongsTo exact one User.

Meetings

class Meeting extends Model { 
protected $table = 'meetings';
protected $primaryKey = 'owner_id';

/**
 * A meeting belongs to exact one User
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 */
public function user(){

    return $this->belongsTo(User::class, 'id');
}}

User

class User extends Authenticatable
{
use Notifiable;

protected $table = 'users';
protected $primaryKey = 'id';

/**
 * One User can have many Meetings
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function meetings(){

    return $this->hasMany(Meeting::class, 'owner_id');
}

I fetch the data with

$meetings = Meeting::with('user')->get();

But somehow i don't get the related user. It just iterates over all users in the database and breaks if no more user is given.

What the heck am I doing wrong? O.o

Upvotes: 0

Views: 859

Answers (2)

Sang Nguyen
Sang Nguyen

Reputation: 1720

Let try to change it:

public function user(){

    return $this->belongsTo(User::class, 'id');
}

To

public function user(){

    return $this->belongsTo(User::class, 'owner_id', 'id');
}

Upvotes: 1

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111889

Looking at your Meeting model there are 2 strange things:

protected $primaryKey = 'owner_id';

Why is that? Shouldn't it be id here?

Second thing:

public function user(){

    return $this->belongsTo(User::class, 'id');
}

probably here instead of id you should user owner_id.

So to sum up it seems you set wrong keys for primary key and for relationships and probably that's the reason relationship doesn't work as it should.

Upvotes: 0

Related Questions