您好,谢谢您的时间和帮助。我有三张很简单的桌子。一个带有user_id的用户表,一个带有game_id以及其他字段(计划日期/时间)的游戏表,以及一个只有user_id和game_id字段的GamesAttendee表。我试图选择所有的游戏,用户是连接的,并只返回那些计划的未来/过去。
最后我要说的是:
$cur = GamesAttendee::where('user_id',$user_id)->pluck('game_id')->all();
$cur = Game::whereIn('id', $cur)->where('scheduled','>=',$now)->get();但我觉得必须有一种更有效的方法来做到这一点。我环顾四周,尝试过各种各样的东西,比如急于装货和捣乱我的模型,但似乎没有什么效果。我觉得这是一个非常简单和基本的例子,非常普遍,我想知道这是怎么做的,实际上是用拉拉。
我试过:
$cur = Game::with(['attendees'=>function($q) use ($user_id){ return $q->where('user_id',$user_id); }])->where('scheduled','>=',$now)->get();
但这不是我想要的。我基本上想做的是:
SELECT * FROM GameAttendees
JOIN `games` on games.id = GameAttendees.game_id
WHERE GameAttendees.user_id = 'x' AND games.scheduled >= '2016/05/01' ;我很快就记下了mysql代码,所以只需忽略任何错误。有什么想法吗?
谢谢。
更新:
通过在我的用户模型中添加以下内容解决了问题:
public function future_games()
{
$now = gmdate('Y-m-d H:i:s',strtotime('+4 hours'));
return $this->belongsToMany('App\Game','games_attendees')->where('scheduled','>=',$now);
}然后,在我的控制器里,我能够做到:
$future_games = User::with('future_games')->get();发布于 2016-05-10 12:30:52
首先,在游戏和用户模型中定义多到多的关系:
class Game extends Model {
public function users() {
return $this->belongsToMany(User::class, 'GameAttendees');
}
}
class User extends Model {
public function games() {
return $this->belongsToMany(Game::class, 'GameAttendees');
}
}有了这一点,您应该能够得到所有的游戏,用户正在参加的:
$games = $user->games;如果要添加一些附加条件,请执行以下操作:
$futureGames = $user->games()->where('scheduled','>=',$now)->get();或者在用户模型中创建另一个关系:
class User extends Model {
public function futureGames() {
return $this->belongsToMany(Game::class, 'GameAttendees')->where('scheduled','>=',$now);
}
}并通过以下方式进入:
$futureGames = $user->futureGames;https://stackoverflow.com/questions/37123812
复制相似问题