【问题标题】:How do I get all related rows from a third relationship table in Eloquent?如何从 Eloquent 中的第三个关系表中获取所有相关行?
【发布时间】:2014-10-29 08:31:31
【问题描述】:

我有三张桌子,experiencesimagesexperience_images

experience_images 中有两列,experience_idimage_id。此表可以为一次体验保存多张图片,如下所示:

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

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

【问题讨论】:

    标签: laravel laravel-4 eloquent laravel-5


    【解决方案1】:

    你必须在你的 Eloquent 模型中建立关系

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

    In the Official Docs

    【讨论】:

    • @Marwelln 这些隐式外键真的有必要吗?通常你可以留下它们,按照惯例,它需要小写的模型名称 + '_id'
    • 在我的例子中,我的两个模型都被命名为Model,但我想它可以被跳过,因为你的例子中的模型被命名为ExperienceImage。如果您愿意,可以恢复我的编辑。
    • 啊,好吧,我以为你有传统的型号名称
    • 我将其命名为 App\Models\Experience\Model。 :-)
    【解决方案2】:

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

    $exp = Experience::find(6);
    
    foreach($exp->images as $e){
    
           return $e->somedata;
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-05
      • 2017-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多