I needed to create a relationship from one user to another for something similar.
i based it off of this:
Hello!
I am developing a sponsoring system for an app. So when a user registers, he has the possibility to be sponsored by another user, and I am having trouble wrapping my head around how to make such a relationship.
Basically, I have a User model as well as a UserSponsored model. The relationship I am trying to create is as such:
A User can have many UserSponsored (beneficiaries) and a UserSponsored can have one User. One To Many right? Except they are really both a Usermodel.
Here's what the users_sponsored table looks like:
users_sponsored:
- id
- sponsor_id // the sponsor user
- beneficiary_id // the benefiacry user
What I really to do is a relationship where a sponsor User is linked to another beneficiary User by using the above intermediate table.
Is there a way to implement that kinda relationship with Eloquent? I feel like I'm going the wrong way with this... How would you implement such a system?
Thanks a lot for your attention. Matthieu
You don't really need an additional table or model for the functionality you describe.
Typically you would set up your users table to be self-referential.
To achieve that you need an additional column in your users table (sponsor_id), which holds the information, who its parent is.
Your User model would look like this:
public function parent()
{
return $this->belongsTo('App\User', 'sponsor_id');
}
public function children()
{
return $this->hasMany('App\User', 'sponsor_id');
}
As you can see a user can have many children (beneficiaries), but only one parent (sponsor).
Hope that helps!
Please or to participate in this conversation.