私は3つの関連モデルから情報を引き出す必要がある方法があります。私は動作する解決策がありますが、N + 1のクエリの問題に悩まされています(また、正しくロードすることができるかどうかを確認する方法についてのソリューションも探しています)。正しくロードしていますか? (Eloquent)
3つのモデルは、チャレンジ、エントランス、ユーザーです。
チャレンジモデルが含まれています
/**
* Retrieves the Entrants object associated to the Challenge
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function entrants()
{
return $this->hasMany('App\Entrant');
}
応募モデルは含まれています
/**
* Retrieves the Challenge object associated to the Entrant
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function challenge()
{
return $this->belongsTo('App\Challenge', 'challenge_id');
}
/**
* Retrieves the User object associated to the Entrant
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo('App\User', 'user_id');
}
とユーザーモデルが含まれています
/**
* Retrieves the Entrants object associated to the User
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function entrants()
{
return $this->hasMany('App\Entrant');
}
私は積極的なロードを使用しようとしています方法は次のようになります:
/**
* Returns an array of currently running challenges
* with associated entrants and associated users
* @return array
*/
public function liveChallenges()
{
$currentDate = Carbon::now();
$challenges = Challenge::where('end_date', '>', $currentDate)
->with('entrants.user')
->where('start_date', '<', $currentDate)
->where('active', '1')
->get();
$challengesObject = [];
foreach ($challenges as $challenge) {
$entrants = $challenge->entrants->load('user')->sortByDesc('current_total_amount')->all();
$entrantsObject = [];
foreach ($entrants as $entrant) {
$user = $entrant->user;
$entrantsObject[] = [
'entrant' => $entrant,
'user' => $user
];
}
$challengesObject[] = [
'challenge' => $challenge,
'entrants' => $entrantsObject
];
}
return $challengesObject;
}
は私が感じる私は、ドキュメントが推奨するものに続くように:https://laravel.com/docs/5.5/eloquent-relationships#eager-loading
をしかし、私は反対しN + 1つのクエリを作っていないよ確認するためにチェックする方法がわからないように、コードにだけ2.任意のヒントや提案へ熱心な読み込みが正しく機能していることを確認する方法とともに、歓迎します。
もしあなたが熱心な読み込みの動作を知りたいのであれば、( 'entrants.user')で ' - > 'を使った後に' $ challeng'変数をダンプし、メソッドを使わないでください。結果を調べる。'dd($ challenge)' –