最近我遇到了访问和过滤深层嵌套关系的问题,所以我决定寻求帮助。
所以,我有这样的db结构:http://s21.postimg.org/motrjy3dj/Screenshot_from_2015_07_24_12_14_51.png
我需要得到一个项目中的所有团队,然后对于每个团队,我需要得到分配的用户(该团队的)。
到目前为止一切顺利,当我试图获得每个用户的报价时,我的问题开始了。用户只能为指定的团队提供一个报价,这给我带来了一个问题。
下面是我的代码:$project = Project::with("variants")
->with(array(
"teams" => function($query) {
$query->with(array(
"users" => function($query) {
$query->with("offers");
}
));
}
))
->find($projectID);
我在"User"模型中有一个hasManyThrough关系"offers",它为用户返回所有报价,但实际上我只需要(一个)相关team_user表的报价。
我试着用范围过滤报价,但这是一个糟糕的解决方案,因为对于每个用户,我都有额外的查询db..
是否有办法动态过滤这些优惠?
谢谢!
对于这种复杂的查询,我强烈建议使用连接:
$projectOffers = Project
->join('team', 'team.project_id', '=', 'project.id')
->join('team_user', 'team_user.team_id', '=', 'team.id')
->join('user', 'user.id', '=', 'team_user.user_id')
->join('offer', 'offer.id', '=', 'team_user.offer_id')
->get([
'project.id',
'team.id AS team_id',
'user.id AS user_id',
'offer.id AS offer_id',
// any other columns you want
]);