我有 3 张桌子 - 挑战、challenge_users和攀登,定义如下:
table challenge
id, name, start_date, end_date
table challenge_users
id, challenge_id, user_id
table climbs
id, user_id, date
我想为挑战中的任何用户提取挑战日期内的攀登列表。 以下 SQL 查询执行我想要的操作:
select
*
from
climbs c
join
challenge_user cu on c.user_id=cu.user_id
where
date >= '2015-03-01'
and date <= '2015-03-06'
and cu.challenge_id=1;
我可以使用查询构建器构建它,例如
$climbs = DB::table('climbs')
->join('challenge_user', 'climbs.user_id', '=', 'challenge_user.user_id')
->where('climbs.date', '>=', $this->start_datetime->tz($tz)->startOfDay()->toDateString())
->where('climbs.date', '<', $this->end_datetime->tz($tz)->endOfDay()->toDateString())
->where('climbs.date', '<=', Carbon::now()->tz($tz)->endOfDay()->toDateString())
->get();
问题是,这返回了一个数组数组。 我真正想要的是获得一个Climb模型集合。 我知道我可以做一些类似 Climb::all()->filter(...) 的事情,但随后我正在做一个相当大的选择(SQL 查询最终只是"从攀爬中选择 *")。
有没有办法使用数据库来限制我的结果,但仍然获得我的攀爬模型集合?
您可以将 Eloquent 与连接一起使用,但需要手动指定 select 语句,以便仅从父表中获取字段,而不是从连接表中获取字段:
$climbs = Climb::select('climbs.*')
->join('challenge_user', 'climbs.user_id', '=', 'challenge_user.user_id')
->where('climbs.date', '>=', $this->start_datetime->tz($tz)->startOfDay()->toDateString())
->where('climbs.date', '<', $this->end_datetime->tz($tz)->endOfDay()->toDateString())
->where('climbs.date', '<=', Carbon::now()->tz($tz)->endOfDay()->toDateString())
->get();