【问题标题】:Laravel 5: how to prefill response from hasMenyLaravel 5:如何预填充来自 hasMeny 的响应
【发布时间】:2017-03-22 11:22:05
【问题描述】:

我是 Laravel 的新手,我找不到下一步该怎么做: 有实体书籍、章节和 Recepis。

Recepis 属于 book_id FK 的书。 章节属于 book_id FK 的书。

Recpies 和章节不通过 DB 链接。但我需要将它们与下一个逻辑联系起来。每个 Recepi 都有位于书中的页码,并且每章的页码范围从strat_page 到 end_page。

当我从控制器调用 book->find(id) 时,我需要获取如下 json:

{
            "id": 132,
            "isbn": "xxx-xx-xx-xxx-x",
            "title": "Bartje BOOK”,
            "author_id": 8,
            "publisher_id": 6,
            chapters:[
                {
                    title : "kidkdk"
                    startpage: 1
                    endpage: 10
                    recepis: [
                        {
                            recepie_id: 1,
                            title: "uyuy",
                            image: "http://kfsklkldkfldkf"
                        },
                        {
                            id: 2,
                            title: "ysysy",
                            image: "http://kfsklkldkfldkf"
                        }
                    ]
                }
            ]
        }

是否有可能在 Book->chapters() 方法中做一些逻辑?

【问题讨论】:

    标签: php laravel laravel-eloquent


    【解决方案1】:

    请按照以下方式制作数据库结构

    • 书籍 -- id,book_name,...
    • 章节 -- id,book_id,chapter_name,....
    • Recepis -- id,chapter_id,recepis_name,....

    现在在模态中建立关系

    • 在书中模式

      公共函数章节(){ 返回 $this->hasMany(Chapters::class,'book_id'); }

    • 在章节模式中

      公共函数 Recepis(){ return $this->hasMany(Recepis::class,'chapter_id'); } -- 现在在控制器写入中..

      $data = Book::with(['Chapters'=>function($q){return $q->with('Recepis');}])->find($id);

    您将根据您的问题获得一个对象 我希望你明白了。

    【讨论】:

    • 这很好,但这是现有项目,我现在需要为章节实体添加广告,而不需要更新现有的接收数据。
    • 您好,如果您想要这种类型的输出,那么您必须更新这种类型的相关性.. 其他方式是您可以简单加入..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    • 2018-10-13
    • 1970-01-01
    • 2018-10-10
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    相关资源
    最近更新 更多