dtrt2368 2016-09-30 18:39
浏览 46
已采纳

通过父母的Laravel关系

I created a model for services that are packed with modules and each modules has a price. Multiple modules create the price for that service.

- Service #1
-- Module 1 ($20)
-- Module 2 ($40)

Using belongsToMany

class Services extends Model
{
    public function modules()
    {
        return $this->belongsToMany('App\Services\Modules');
        ...

each module links to a price

class Modules extends Model
{
    public function price()
    {
        return $this->hasOne('App\Services\Pricing', 'product')->where('type', 'module');
        ...

and a service_module table that links services to modules. The problem is what kind of relationship should I create to be able to ->sum() the module prices for each service because I created an ugly patch with loops and burning 15 more queries per request

$prices = [];
foreach ($services->modules as $modules )
    $prices[] = $modules ->price['month'];
$price = number_format(collect($prices)->sum(), 2, '.', '');
  • 写回答

1条回答 默认 最新

  • dongyan1993 2016-10-01 00:51
    关注

    You can use Eager Loading to load your relationships along with the services query to turn those 15 extra queries into one extra query.

    Code examples in the linked docs should be enough to get you started.

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

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作