Laravel雄辩的图像/页面关系设置



我正在搬到Laravel,并认为学习的最佳方法是在Laravel中重建我自己的CMS,但我正在努力以下内容:

我正在使用Laravel 5.4

我有五个表(设置了相应的型号(:

images (id, type_id, item_id)
images_types (id)
images_types_templates (type_id, template_id)
pages (id, template_id)
templates (id)

我正在尝试建立一种雄辩的关系,以便我可以在Tinker中运行它:

Page::with(['images'])->first()

并查看此页面的相关图像(item_id(和template_id

到目前为止,我只能在我的模型中检索项目:

public function images()
    {
        return $this->hasMany('AppImage', 'item_id');
    }

这确实有效,但是它仅检索匹配images.item_id

的页面。

我需要检查 images.type_id 与当前页面匹配。这是从 pages 表( pages.template_id (设置在此页面上(

我希望我可以运行页面::(['images'](,并且仅查看与此页面和template_id有关的图像。 item_id 图像中的字段表可以与网站的任何其他部分有关,而不仅仅是页面,这就是为什么它是 item_id 和不 pag_id

希望有意义

我已经弄清楚了。

所以在我的页面上。我有:

public function template()
{
    return $this->hasOne('AppTemplate', 'id', 'template_id');
}

然后在我的template.php模型上:

public function type(){
    return $this->belongsToMany(ImageType::class,'images_types_templates','template_id', 'type_id');
}

我可以在小叮当中运行此操作:

Page::with(['template', 'template.type'])->get()

,它返回以下内容:

AppPage {#752
     id: 1,
     template_id: 1,
     parent_id: 0,
     slug: "home",
     title: "Home",
     subtitle: null,
     menu_title: "Home",
     content: null,
     meta_title: "Home",
     meta_description: null,
     meta_keywords: null,
     show_in_nav: 1,
     published: 1,
     created_at: null,
     updated_at: null,
     template: AppTemplate {#759
       id: 1,
       title: "Homepage",
       filename: "home",
       selectable: 0,
       created_at: "2018-02-09 09:17:53",
       updated_at: null,
       type: IlluminateDatabaseEloquentCollection {#763
         all: [
           AppImageType {#771
             id: 1,
             title: "Banners",
             path: "banners",
             pivot: IlluminateDatabaseEloquentRelationsPivot {#766
               template_id: 1,
               type_id: 1,
             },
           },
         ],
       },
     },
   },

:(

最新更新