简体   繁体   中英

Laravel eloquent relationship (one-to-one)

Can you please help me with this error, I am using laravel version 5.2.*. I have setup a One-to-One relation between a student and an application. Please see the code below.

Student Model:

public function application() {
    return $this->hasOne('App\Application');
}

Application Model:

public function student() {
    return $this->belongsTo('App\Student');
}

The database is correctly setup, I have a student_id FK in the Applications table. However, I am still getting the following error. What am I doing wrong, what did I miss? this worked before, it just broke all of a sudden.

BadMethodCallException in Builder.php line 2146: Call to undefined method Illuminate\\Database\\Query\\Builder::applications()

I get the error when I try to insert into the applications table, ie When trying to create an application for the student with the code below.

$student = new Student;
//There's code to insert into the students table here
$application = new Application([
            'academic_year_id' => $year,
            'ref_no' => Application::getReferenceNumber($year)->Ref_no,
            'certificate_id' => 1, //This will remain hard coded until the centre starts to offer more than one certificate
            'status' => "PENDING",
            'slug' => str_slug(Application::getReferenceNumber($year)->Ref_no . "" . $academic_year->year)
        ]);
        $student->applications()->save($application); //Insert into the application table

In Student model your function name is application not applications . So change your code

$student->application()->save($application);

instead of

$student->applications()->save($application);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM