雄辩的渴望加载自定义属性

Context: I'm using Lumen to build a JSON API and am looking to make the requests as small as possible

I am unable to work out how to conditionally append an eloquent model attribute when loading.

My example is quite complex to explain - so I will try and boil it down to a more simple explanation.

Let's take an example of Categories, Posts and Comments.

In terms of relations:

  • Categories has many Posts.
  • Posts does have Comments, but for various reasons this isn't a simple relationship and requires some custom filtering and joining.

Question 1: I have "attached" the comments to posts via an attribute - is this correct?

I have used the getCommentsAttribute method and added comments to the appends array on the model.

However, when listing all the Posts in a category, the Comments come along for the ride - thus making the JSON a rather large file (many posts with many categories).

I realise this is because they are being automatically appended and remove it from the appends array.

However, I then struggle to get them back. If I wanted a different category list with the comments included, I can't seem to reference them

Categories::find(2)->with([
    'posts'
]);

I've tried adding a query after posts and using other with statements but can't seem to access the comments.

Question 2: How do you conditionally add attributes to an eager load statement, to load them on certain requests?