starmatt's avatar

A One-To-Many relationship between an user and other users ?

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

0 likes
5 replies
Exiax's avatar
Exiax
Best Answer
Level 3

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!

3 likes
Cronix's avatar

@Exiax I don't understand how one user can have many sponsors using your example since you're only adding a single sponsor_id to the users table. How does a single user store many sponsors in the Users table using a single sponsor_id field?

Say a user with id of 1 has several sponsors with id's of 2, 4 and 10?

1 like
Exiax's avatar

@Cronix A user can't have many sponsors using my example. A user only can have one sponsor, but a sponsor can have multiple beneficiaries .

That should reflect the use-case @starmatt was describing, unless i got something wrong:

So when a user registers, he has the possibility to be sponsored by another user

and

The relationship I am trying to create is as such: A User can have many UserSponsored (beneficiaries) and a UserSponsored can have one User.

If a user should be allowed to have many sponsors, additionally to a sponsor having multiple beneficiaries, then you would of course need to set up a many-to-many relationship.

1 like
starmatt's avatar

@Exiax Yep, it was pretty simple in the end.

Thanks for everybody for your input!

Please or to participate in this conversation.