深度嵌套关系过滤
Deeply nested relationships filtering
最近我在访问和过滤深层嵌套关系时遇到问题,所以我决定寻求帮助。
所以,我有这个数据库结构:
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",returns 我为用户提供所有优惠,但实际上我只需要(一个)相关 team_user table.
我尝试使用范围过滤商品,但这是一个糟糕的解决方案,因为对于每个用户,我都有额外的数据库查询..
有什么方法可以动态过滤这些优惠吗?
谢谢!
我强烈建议对此类复杂查询使用联接:
$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
]);
最近我在访问和过滤深层嵌套关系时遇到问题,所以我决定寻求帮助。
所以,我有这个数据库结构: 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",returns 我为用户提供所有优惠,但实际上我只需要(一个)相关 team_user table.
我尝试使用范围过滤商品,但这是一个糟糕的解决方案,因为对于每个用户,我都有额外的数据库查询..
有什么方法可以动态过滤这些优惠吗?
谢谢!
我强烈建议对此类复杂查询使用联接:
$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
]);