I am building a referral system, the table User is referred by another, for example:
User table:
id
name
Referrals table:
id
referred_by (user_id)
refers_to (user_id)
Same foreign key to the same table. Which are the relationships between User table and Referrals?
I am assuming your user model is App\User
and your Referral model is App\Referral
:
If you want to get, via your user, who they have referred you can do in App\User
:
function referredBy() {
return $this->hasMany('App\Referral', 'referred_by');
}
If you want to get, via your user, who they were referred by:
function referredTo() {
return $this->hasMany('App\Referral', 'refers_to');
}
Anywhere you have a $user
object, you can get a list of all other referenced users by $user->referredTo()
or $user->referredBy()
The Eloquent models allow you to create many different style relations with different key names.
Reference: https://laravel.com/docs/5.5/eloquent-relationships#introduction
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments