【发布时间】:2018-10-31 00:59:43
【问题描述】:
我的应用程序:在我的应用程序中,用户可以预测即将到来的足球比赛的比分。所以基本上user和predictions之间有关系,但prediction和我的Match model之间也有关系。目前我在我的预测表中添加了homeTeamName 和awayTeamName,但这并不是必需的,因为我将match_id 存储在我的预测表中。我想根据我的预测表中的match_id 从我的match table 加载我的团队名称,而不是在预测表中添加名称。
这是我的关系:
匹配模型
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
]
]
【问题讨论】: