Reputation: 1150
I'm doing a project for one of my University courses. But I'm finding it difficult to make relationship between User
to User
model.
Table: users
On this table the column type
is used for classifying user types.
For example: User can be either distributor
or dealer
type.
And a distributor
may have many dealer
But a dealer
may have only one distributor
.
To implement this I've created another table and named as dealers_of_distributor
.
Table: dealers_of_distributor
Although I've used an additional model DelaersOfDistributor
, the exact relationship should be between user
to user
.
How can I make this relationship. I'm confused!
I've tried so far:
Model: User
public function dealersOfDistributor(){
$this->hasMany('App\DealersOfDistributor');
}
Model: DealersOfDistributor
public function user(){
return $this->belongsTo('App\User');
}
The DistributorsController
public function index()
{
$distributors=User::where('type', 'distributor')->get();
$dealers=User::where('type', 'dealer')->get();
$assignedDealers=DealersOfDistributor::all();
return view('distributors.index')->withDistributors($distributors)->withDealers($dealers)->with('assignedDealers', $assignedDealers);
}
In blade
file: I've tried $assignedDealer->dealer_id->user->name
. But It's showing error.
Upvotes: 0
Views: 1015
Reputation: 105
Model DealersOfDistributor:
public function distributorUser()
{
return $this->belongsTo('App\User', 'distributor_id', 'id');
}
public function dealerUser()
{
return $this->belongsTo('App\User', 'dealer_id', 'id');
}
than you just get the user's data from DealersOfDistributor model, call function dealerUser if you want get user's data from dealer_id, and call function distributionUser if you want get user's data from distribution_id
Controller:
public function index()
{
$assignedDealers=DealersOfDistributor::all();
return view('distributors.index',compact('assignedDealers'));
}
Blade get username:
@foreach($assignedDealers as $assign)
{{$assign->distributorUser->name}}
{{$assign->dealerUser->name}}
@endforeach
Upvotes: 1