Мое приложение: В моем приложении пользователи имеют возможность прогнозировать результаты предстоящих футбольных игр. Таким образом, в основном существует связь между user
и predictions
, но есть также связь между prediction
и моим Match model
. В настоящее время я добавляю homeTeamName
& awayTeamName
в свою таблицу прогнозирования, но это не является действительно необходимым, поскольку я храню мой match_id
в моей таблице прогнозирования. Я хочу загрузить имена своих команд из моих match table
на основе match_id
из моей таблицы прогнозов вместо того, чтобы добавлять имена в таблицу прогнозов.
Вот посмотрите на мои отношения:
Матч модель
class Match extends Model
{
public function Predictions() {
return $this->hasMany('App\Prediction'); // one match has many predictions
}
}
Модель прогноза
class Prediction extends Model
{
public function User() {
return $this->belongsTo('App\User'); // prediction belongs to a user
}
public function Match() {
return $this->belongsTo('App\Match', 'match_id', 'match_id'); // prediction belongs to a match
}
}
Модель пользователя
class User extends Authenticatable
{
public function Predictions() {
return $this->hasMany('App\Prediction'); // a user has many predictions
}
}
Использование отложенной загрузки для этого запроса
public function showPredictions() {
\DB::enableQueryLog();
$user = Auth::user();
$user->load('predictions', 'predictions.match');
dd(\DB::getQueryLog());
return view('predictions', compact('user'));
}
выход
array:3 [▼
0 => array:3 [▼
"query" => "select * from `users` where `id` = ? limit 1"
"bindings" => array:1 [▼
0 => 1
]
"time" => 13.0
]
1 => array:3 [▼
"query" => "select * from `predictions` where `predictions`.`user_id` in (?)"
"bindings" => array:1 [▼
0 => 1
]
"time" => 1.0
]
2 => array:3 [▼
"query" => "select * from `matches` where `matches`.`id` in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
"bindings" => array:10 [▼
0 => 233133
1 => 233134
2 => 233135
3 => 233136
4 => 233137
5 => 233138
6 => 233139
7 => 233140
8 => 233141
9 => 233142
]
"time" => 1.0
]
]