Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

afrasiyabhaider's avatar

One model having 'hasMany' relation with multiple model

I have a student model in which I've created these two relations

- Student Model

    public function previous_academic_record()
    {
        return $this->hasMany(previous_academic_record::class);
    }
    public function student_guardians()
    {
        return $this->hasMany(student_guardians::class);
    }

I have two more models named as

  • previous_academic_record
  • student_guardians

which belongsTo students

- In the student guardian model

public function students()
    {
        return $this->belongsTo(students::class);
    }

- in the previous academic record model 

public function students()
    {
        return $this->belongsTo(students::class);
    }

now please tell me how to save records

when I write below code it does not save student_id (does not create a reference to student)

 $student = new stduents();

$student->previous_academic_record()->create([]);

and 

$student->studnet_guardians()->create([]);

Please tell me how to figure this out

0 likes
2 replies
Sti3bas's avatar

$student = new Student(); will not create a model, it will only instantiate a model class, so the instance will not have id, because id is only set after you save a model to the database.

afrasiyabhaider's avatar
Level 2

@ there is a code for storing student but it is still not working

$student->save();

Please or to participate in this conversation.