duanke3985 2014-02-04 12:15
浏览 41
已采纳

Laravel Relationship并在结果集中为每个条目提供前几个条目

There is a car dealers listing with pagination where I need to show first 3 cars with that car's manufacturer and model no of that dealer. Its like

Car Dealer 1

  • car 1 -> Fetching car's Manufacturer from manufacturer table and model from model table
  • car 2 -> Fetching car's Manufacturer from manufacturer table and model from model table
  • car 3 -> Fetching car's Manufacturer from manufacturer table and model from model table

Car Dealer 2

  • car 1 -> Fetching car's Manufacturer from manufacturer table and model from model table
  • car 2 -> Fetching car's Manufacturer from manufacturer table and model from model table
  • car 3 -> Fetching car's Manufacturer from manufacturer table and model from model table

and so on with pagination

Its obvious that querying in loop is not a good solution. Is there any good work around this problem?

I have checked hasManyThrough but it does not suits here.

its kind a query : get first 3 cars with manufacturer and model nos for each dealers in resultset. If Laravel relationship does not work then what queries should be used to avoid looping? Thanks

  • 写回答

1条回答 默认 最新

  • douluo3256 2014-02-04 12:46
    关注

    You want to eager load the cars and their properties.

    Dealer::with(['cars', 'cars.models', 'cars.makes'])->get();

    Now you can iterate as much as you need to. The query counts won't increase.

    Sorry for short answer. On phone :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作