Reputation: 456
This is my scenario.
I've a table named 'team' and the laravel 'user' table.
I'm trying to make two relationships between team and user one for 'owner' and the other for 'manager'
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Team extends Model
{
protected $table = 'team';
public function owner(){
return $this->belongsTo(User::class, 'id');
}
public function manager(){
return $this->belongsTo(User::class, 'id');
}
}
But it seems that something is not working as I expected, how to do this in the right way? thanks.
Upvotes: 1
Views: 3113
Reputation: 538
You can't do this with same id, you need to create 2 column owner_id and manager_id for user table then you relate tables
public function owner(){
return $this->belongsTo('App\User','id','owner_id');
}
public function manager(){
return $this->belongsTo('App\User','id','manager_id');
}
Upvotes: 6
Reputation: 3563
How would Laravel know who is the owner and who is the manager? How does your database structure look like?
In your current scenario, the owner() and manager() function would return the same results.
Also, in your current setup, it would mean that a Team belongs only to one User (further, you say that your foreign key is stored in the column id
which usually is the primary key).
I think what you need is a ManyToMany Relationship between User and Team and an intermediate table that stores the Role that the User has within a team. If a user is only member to one team at a time, the User belongsTo
the team, and his role could be saved in a separate field in the User table.
Some advice:
1) Be more specific about your problem. "something is not working as I expected" is not specific, and it does not help us to understand what you want to do and what actually happened
2) Read the Laravel Documentation. https://laravel.com/docs/5.5/eloquent-relationships
Upvotes: 0
Reputation: 7334
You can have a flag set on users table to tell you which one represent the team and manager, say role
then update your relationship with additional scope methods like :
public function user(){
return $this->belongsTo(User::class, 'id');
}
public function scopeManager(){
return $this->user()->where('role', 'manager');
}
public function scopeOwner(){
return $this->user()->where('role', 'owner');
}
This means you can setup a relationship between User and Team and set a filter on what type of user you are referring to:
$manager = Team::first()->manager()->get();
//same for owner
Not sure this is a very comprehensive answer but I am pretty sure it should suffice.
Anything missing please point them out.
Upvotes: 0