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?

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.