【发布时间】:2016-07-23 22:32:31
【问题描述】:
用户可以注册多个锦标赛和 每个锦标赛的每个用户都有一个分数记录。
我将 user_id 保存在 Score 表中以保持记录的唯一性。
我有这个查询:
$tournaments = DB::table('tournaments')
->join('scores','tournaments.id','=','scores.tournament_id')
->select('tournaments.*','scores.score','scores.tees')
->where('t_date','<',Carbon::today())
->where('scores.user_id',$request->user()->id)
->get();
我想避免连接并使用查询范围来重复使用 where 子句'(t_date < Carbon::today())'
所以,这是我想出的查询:
//This is in Tournament Model
public function scopeUpcoming($query)
{
return $query->where('t_date','>',Carbon::today());
}
$query = Score::with('tournaments')
->upcoming()
->where('user_id',$request->user()->id)
->get();
但是 scopeUpcoming() 使用 $query 并且 Score 表中没有 't_date',所以我需要以某种方式访问锦标赛表并对其进行查询。反之亦然,我不能使用 Tournament::with('scores'),因为 Tournament 的表格中没有 'user_id',所以我无法获取特定用户。
【问题讨论】:
-
那么避免加入的原因是什么?
-
我的控制器中有很多连接,我发现连接和原始查询是一种 hack,我很少使用 Eloquent 模型。我想以设计使用的方式学习 MVC 框架。我试图避免单/多连接,并希望更有效地使用雄辩的关系。
标签: php mysql laravel laravel-5.2