我想按日拉出认捐的NPC。但是,为此,我需要使用地牢名称。 İ有3张桌子。
Npcs表:
id | name
-----------
1 | NPC 1
2 | NPC 2
3 | NPC 3
地下城表
id | name
---------------
1 | Dungeon 1
2 | Dungeon 2
3 | Dungeon 3
4 | Dungeon 4
5 | Dungeon 5
6 | Dungeon 6
认捐表
id | npc_id | dungeon_id | date
------------------------------------------
1 | 1 | 1 | 2019-05-26
2 | 2 | 2 | 2019-05-26
3 | 3 | 3 | 2019-05-26
4 | 1 | 4 | 2019-05-27
5 | 2 | 5 | 2019-05-27
6 | 3 | 6 | 2019-05-27
我的控制器代码;
public function index()
{
$y = Carbon::yesterday('Europe/London');
$t = Carbon::today('Europe/London');
$time = Carbon::now('Europe/London');
$yesterday = Carbon::create($y->year, $y->month, $y->day, 10, 0, 0); //set time to 10:00
$today = Carbon::create($t->year, $t->month, $t->day, 10, 0, 0); //set time to 10:00
if($time->between($yesterday, $today, true)) {
$pledges = Npc::join('pledges', function ($join) {
$join->on('npcs.id', '=', 'pledges.npc_id')
->where('pledges.date', '=', Carbon::yesterday('Europe/London'));
})
->get();
return $pledges;
} else {
$pledges = Npc::join('pledges', function ($join) {
$join->on('npcs.id', '=', 'pledges.npc_id')
->where('pledges.date', '=', Carbon::today('Europe/London'));
})
->get();
return $pledges;
}
}
这段代码为我提供了以下结果。
0
id 5
name "NPC 1"
created_at "2019-05-27 11:35:27"
updated_at "2019-05-27 11:35:27"
npc_id 1
dungeon_id 1
date "2019-05-27"
但是我需要这个结果的地牢名称。
答案 0 :(得分:1)
您应该使用其他联接+选择。试试这个。
public function index()
{
$time = Carbon::now('Europe/London');
$yesterday = Carbon::yesterday('Europe/London')->setTime(10, 0, 0);
$today = Carbon::today('Europe/London')->setTime(10, 0, 0);
if($time->between($yesterday, $today, true)){
$date = $yesterday;
} else {
$date = $today;
}
$pledges = Npc::select('npcs.*', 'dungeons.id as dungeon_id', 'dungeons.name as dungeon_name')
->join('pledges', function($join) use ($date) {
$join->on('npcs.id', '=', 'pledges.npc_id')->where('date', $date);
})
->join('dungeons', 'dungeons.id', '=', 'pledges.dungeon_id')
->get();
return $pledges;
}