dtmm0148603 2018-10-25 08:48
浏览 26

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

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?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
    • ¥20 关于URL获取的参数,无法执行二选一查询
    • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
    • ¥15 marlin编译错误,如何解决?
    • ¥15 有偿四位数,节约算法和扫描算法
    • ¥15 VUE项目怎么运行,系统打不开
    • ¥50 pointpillars等目标检测算法怎么融合注意力机制
    • ¥20 Vs code Mac系统 PHP Debug调试环境配置
    • ¥60 大一项目课,微信小程序
    • ¥15 求视频摘要youtube和ovp数据集