dtlhy0771 2017-03-22 11:22
浏览 59

Laravel 5:如何从hasMeny预备填充响应

I'm new in Laravel and I can't found how to do next: There are entites Books, Chapters and Recepis.

Recepis belongs to book by book_id FK. Chapters belongs to book by book_id FK.

Recpies and Chapters are not linked through DB. But I need to linke them on next logic. Each Recepi has page number where is located in book and each chapter has range of pages strat_page to end_page.

When I call book->find(id) from controller I need to get json like:

{
            "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"
                        }
                    ]
                }
            ]
        }

Is there any posibility to do some logic in Book->chapters() method?

  • 写回答

1条回答 默认 最新

  • dongyi2534 2017-03-22 11:50
    关注

    Please Make a DB Structure as per below

    • Books -- id,book_name,...
    • Chapters -- id,book_id,chapter_name,....
    • Recepis -- id,chapter_id,recepis_name,....

    Now in modal make a relationship

    • In Books Modal

      public function Chapters(){ return $this->hasMany(Chapters::class,'book_id'); }

    • In Chapters Modal

      public function Recepis(){ return $this->hasMany(Recepis::class,'chapter_id'); } -- Now in Controller Write..

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

    You will get a Object as per Your question i Hope you got it.

    评论

报告相同问题?

悬赏问题

  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单