键入一种急切的关系

时间:2018-01-04 14:39:30

标签: laravel laravel-5

我有商业模式和小时模型。商业模式会覆盖protected $with方法以急切加载hours() hasMany关系。

当我::first()给定的业务时,我会收到这样的信息:

App\Business {#770
 id: 5,
 user_id: 5,
 name: "Wehner-Hudson",
 slug: "wehner-hudson",
 lat: "55.33593500",
 lng: "112.34818600",
 created_at: "2018-01-04 13:00:48",
 updated_at: "2018-01-04 13:00:48",
 hours: Illuminate\Database\Eloquent\Collection {#753
   all: [
     App\Hour {#802
       id: 13,
       business_id: 5,
       weekday_id: 3,
       open: 1,
       split_shift: 1,
     },
     App\Hour {#803
       id: 14,
       business_id: 5,
       weekday_id: 5,
       open: 0,
       split_shift: 1,
     },
     App\Hour {#804
       id: 15,
       business_id: 5,
       weekday_id: 2,
       open: 1,
       split_shift: 0,
     },
   ],
 },
},
],
}

我想通过hours: Illuminate\Database\Eloquent\Collection {#753键入weekday_id以便于在客户端进行处理。像这样:

Illuminate\Database\Eloquent\Collection {#763
all: [
1 => App\Hour {#796
 id: 1,
 business_id: 1,
 weekday_id: 1,
 open: 1,
 split_shift: 1,
},
5 => App\Hour {#767
 id: 2,
 business_id: 1,
 weekday_id: 5,
 open: 0,
 split_shift: 0,
},
2 => App\Hour {#765
 id: 3,
 business_id: 1,
 weekday_id: 2,
 open: 1,
 split_shift: 1,
},
],
}

我尝试在商业模式中使用keyBy:

public function hours()
{
   return $this->hasMany(Hour::class)->keyBy('weekday_id'); 
} 

但是它没有用,因为我相信在那时返回的对象是一个构建器,而不是一个集合。

2 个答案:

答案 0 :(得分:0)

尝试定义一个访问器,如下所示:

public function getHoursByWeekdayAttribute()
{
    return $this->hours->keyBy('weekday_id');
}

答案 1 :(得分:0)

如何在控制器中使用groupby。

Business::with(['hours' => function($query){ $query->groupBy('weekend_id'); }])->get();