如何从Eloquent中的第三个关系表中获取所有相关行?

时间:2014-10-29 08:31:32

标签: laravel laravel-4 eloquent laravel-5

我有三个表,experiencesimagesexperience_images

experience_images我有两列,experience_idimage_id。这张桌子可以容纳许多图像以获得一种体验,如下所示:

"experience_id","image_id"
"6","31"
"6","32"
"6","33"
"6","34"

现在如何通过运行Image从我的Experience模型中获取Experience::find(6)->images的集合?

2 个答案:

答案 0 :(得分:1)

您必须在Eloquent模型中设置关系

class Experience extends Eloquent {
    public function images(){
        return $this->belongsToMany('Image', 'experience_images', 'experience_id', 'image_id');
    }
}

In the Official Docs

答案 1 :(得分:0)

您必须在paremeter find()中添加一个id。在这种情况下是6:

$exp = Experience::find(6);

foreach($exp->images as $e){

       return $e->somedata;

}