Okay let's suppose the Database structure is something similar to this
Table: users
int: user_id
int: invited_by
Where invited_by is a foreign key that references user_id in the same table (users).
I have created the following migration to create the above database structure (p.s you are free to create it using raw MySql query)
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('user_id');
$table->integer('invited_by')->unsigned()->nullable();
$table->foreign('invited_by')
->references('user_id')
->on('users');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
Then I Inserted into users table some test data as following:
user_id: 1, invited_by: null
user_id: 2, invited_by: 1
user_id: 3, invited_by: 1
user_id: 4, invited_by: 1
Now in User eloquent model I have added those two functions:
/**
* Function to get the users that were invited by the current user.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function invitees()
{
return $this->hasMany(User::class, 'invited_by', 'user_id');
}
/**
* Function to get the user who invited the current user.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function invitedBy()
{
return $this->belongsTo(User::class, 'invited_by', 'user_id');
}
Now let's say if I want to know who invited user of ID 2:
$user = User::where('user_id', 2)->first();
$invitedByUser = $user->invitedBy()->getResults();
If we want to know the users that user of ID 1 invited:
$user = User::where('user_id', 1)->first();
$invitees = $user->invitees()->getResults();
I have tried it and it works as expected. Hope this helps.
1and then all the users that they in turn invited?