调用未定义的方法Illuminate \ Database \ Eloquent \ Relations \ HasMany :: associate()

我试图在laravel中建立关系。我想使用一对一和一对多关系添加数据,并将数据保存到数据库。我坚持这是错误的:

Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::associate()

StudentsController.php

public function store(Request $request)
    {
        $this->validate(
        $request,
        [
          'nama' => 'required',
          'nim' => 'required|size:10',
          'tanggal_lahir' => 'required',
          'jenis_kelamin' => 'required',
          'class_student_id' => 'required',
          'telephone' => 'nullable|numeric|digits_between:10,15|unique:telephones,telp_number'
        ],
        [
          'nama.required' => 'Form nama lengkap tidak boleh kosong',
          'nim.required' => 'Form nomor induk siswa tidak boleh kosong',
          'nim.size' => 'Form nomor induk siswa membutuhkan 10 karakter',
          'tanggal_lahir.required' => 'Form tanggal lahir tidak boleh kosong',
          'jenis_kelamin.required' => 'Form jenis kelamin tidak boleh kosong',
          'class_student_id.required' => 'Form kelas tidak boleh kosong'
        ],
      );

      $student = Student::create($request->all());

      $class_student = new ClassStudent;
      $class_student->student()->associate($student);
      $class_student->save();

      $telephone = new Telephone([
        'telp_number' => $request->input('telephone')
      ]);
      $student->telephone()->push($telephone);

      return redirect('students')->with('status', 'Data siswa berhasil ditambahkan');
    }

学生.php

class Student extends Model
{
    protected $fillable = [
      'nim',
      'nama',
      'tanggal_lahir',
      'jenis_kelamin',
      'class_student_id'
    ];

    public function telephone()
    {
      return $this->hasOne(Telephone::class);
    }

    public function classStudent()
    {
        // return $this->belongsTo(ClassStudent::class);
        return $this->belongsTo('App\ClassStudent', 'class_student_id');
    }
}

电话.php

class Telephone extends Model
{
  protected $fillable = ['id', 'telp_number'];

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

ClassStudent.php

class ClassStudent extends Model
{
    protected $fillable = ['id', 'class_name'];

    public function student()
    {
        // return $this->hasMany(Student::class);
        return $this->hasMany('App\Student', 'id');
    }
}

请帮助我从您的简单代码中教给我该任务。 谢谢!

评论
  • 明天H
    明天H 回复

    First of all, you should rename your student relationship to students to reflect the fact it's a to-many relationship (reading student suggests it's a to-one)

    associate is a method used by belongsTo relationships, not hasOneOrMany relationships. You must use save or create instead.

    Full documentation here https://laravel.com/docs/7.x/eloquent-relationships#the-save-method