In laravel referral system i want two foreign keys(userId,parentId) if user registers using referral code
I defined two foreign keys (userId,parentId) in the network table when a user registers with a referral code. It’s id, and its parent ID get saved in network table with userId and parentId, respectively, but I’m finding it difficult, so I recently saw a new method to define a foreign key references on primary key in the same table something like:
$table->foreign('parent_id')
->references('id')
->on('users')
->onUpdate('cascade')
->onDelete('set null');
But not sure how it works, so no guidance.
2
Answers
I believe that what is missing in your syntax are only the fields that will be referenced as soon as the foreign key is created. The field must have already been defined in the table, according to the following code:
If you are also having difficulty creating relationships in models, it would look something like this:
User
Network
for those users who have no referral, they can’t have parent_id. but you have not defined that parent_id can be null. for the current code, it need to have a parent_id.
change parent_id non-null to nullable. here is the updated code