简体   繁体   中英

Laravel Eloquent hasOne returns empty

I have two tables named 'works' and 'slides' as well as two classes that extend Eloquent named 'Work' and 'Slide'. Inside my 'works' table I have a 'id' column, a 'title' column, a 'description' column and a 'image' column and inside my 'slides' table I have a composite key using a foreign key with two columns named 'id' and 'work_id'.

This is how my database relationship looks: 数据库关系

This is the code for my Slide class:

class Slide extends Eloquent {

    public $timestamps = false;

    public function workId() {
        return $this->hasOne('work', 'work_id', 'id');
    }

}

And this is the code for my Work class:

class Work extends Eloquent {

    public $timestamps = false;

}

Inside my index page I am trying to get a Work object by calling the 'workId()' method inside my Slide object however it returns empty with this code:

$slides = Slide::all();
$works = new \Illuminate\Database\Eloquent\Collection;
foreach ($slides as $slide) {
    $works->push($slide->workId());
}
printf($works);

However, if I replace the '$slide->workId()' call with:

Work::find($slide->work_id)

then it finds the row with no problem.

What should I do to get the function to return the Work object rather than calling Work::find()?

Slide belongs to Work because the foreign key to works is inside the slides table. You're also using the incorrect naming for the relationship function and incorrect syntax for the hasOne.

You need to use:

class Slide extends Eloquent {

    public $timestamps = false;

    public function work() {
        return $this->belongsTo('Work');
        //or return $this->belongsTo('Work', 'work_id', 'id');
    }

}

To get the Work that belongs to a Slide: $slide->work

Note: you use " association() " for belongsTo, not "push()"

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