【问题标题】:Laravel Eloquent images/pages relationship setupLaravel Eloquent 图片/页面关系设置
【发布时间】:2018-07-19 06:48:18
【问题描述】:

我正在迁移到 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) AND template_id

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

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

这确实有效,但它只检索与 images.item_id 匹配的 pages.id

而我需要检查 images.type_id 是否与当前页面匹配。这是从 pages 表中设置的(pages.template_id,需要检查 images_types_templates.template_id 以查看是否允许此类图像在此页面上)

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

希望这是有道理的

【问题讨论】:

  • 您的要求令人困惑..您能否重复使用查询返回哪些表以及您希望将此查询放置在哪个模型中
  • item_id 指的是什么?而且,在您的 pages 表中,您有 image_id 列吗?看来你只与 template_id 有关系(表明智)

标签: php laravel laravel-5 laravel-5.4


【解决方案1】:

我想通了。

所以在我的 Page.php 模型上我有:

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

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

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

然后我可以在 tinker 中运行它:

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

它返回这个:

App\Page {#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: App\Template {#759
       id: 1,
       title: "Homepage",
       filename: "home",
       selectable: 0,
       created_at: "2018-02-09 09:17:53",
       updated_at: null,
       type: Illuminate\Database\Eloquent\Collection {#763
         all: [
           App\ImageType {#771
             id: 1,
             title: "Banners",
             path: "banners",
             pivot: Illuminate\Database\Eloquent\Relations\Pivot {#766
               template_id: 1,
               type_id: 1,
             },
           },
         ],
       },
     },
   },

:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-26
    • 2022-06-10
    • 2012-09-27
    • 1970-01-01
    • 2017-03-17
    • 2017-12-27
    • 2020-11-02
    • 2016-08-13
    相关资源
    最近更新 更多