Reputation: 159
I'm using one User table to store the information of three different users. I created the parent first with one parent_id, and now I want to create the student, and I want to give reference of parent id.
My Table has an id, parent_id, name, job, etc. When the parent gets registered, it will set a new id, parent_id, name, job. When the student gets registered, it will set the new id, name, and parent_id stored earlier.
I'm new to Laravel 5.7 and I m having issues with syntaxes to store parent record with student record.
Upvotes: 0
Views: 1633
Reputation: 106
I agree with Ali Mrj Use Ali Mrj style to make relation..
class User extends Model
{
public function parent(){
return $this->belongsTo('App\User','parent_id');
}
public function children(){
return $this->hasMany('App\User','parent_id');
}
}
then you use umefarooq style to insert data. create parent record get its id as parent_id for sudent, then create student record
how can you get the last id? it depends on your style. i thinking about 2 solution right now..
- get all of id_parent then use it in
- get the last id parent from database.
how to get last id_parent?
$last_user = User::where('job','teacher')->orderBy('id','desc')->get()
Upvotes: 0
Reputation: 71
If I understand you correctly, you want to make a user parent of other users. For example a student will have a parent which is also a user. If that is the case you will need your user model to be implemented like below:
class User extends Model
{
public function parent(){
return $this->belongsTo('App\User','parent_id');
}
public function children(){
return $this->hasMany('App\User','parent_id');
}
}
This way you can access children and parent of your users.
Upvotes: 1