1
我读this帮助的帖子,但需要更多的指导。Laravel 5.3雄辩3表连接使用模型
我需要针对特定的$batteryid
(在结果)和特定的$age
(在测试模型上)和特定的$gender
(来自运动员)的一组结果。每个测试都属于一名运动员。每个测试都有很多结果。
型号电池:
class Battery extends Model{
public function results(){
return $this->hasMany('App\Result');
}
}
模型结果:
class Result extends Model{
public function test(){
return $this->belongsTo('App\Test', 'test_id');
}
public function battery(){
return $this->belongsTo('App\Battery', 'battery_id');
}
}
模型试验:
class Test extends Model{
public function athlete(){
return $this->belongsTo('App\Athlete', 'athlete_id');
}
public function results(){
return $this->hasMany('App\Result');
}
}
我出现以下正确的结果,但它的两个查询:
$tests = Test::whereHas('Athlete', function($query) use($gender){
$query->wheregender($gender);
})->where('age', $age)->get();
$test_ids = $tests->pluck('id');
$results = Result::where('battery_id', '=', $battery)
->whereIn('test_id', $test_ids)
->get();
我想使用模型方法,但我完全卡住了。 test.age
没有得到承认,不知道如何从运动员模型中获得年龄。我尝试:
$results = Result::with('test')
->where('test.age', '=', $age)
->join('batteries', 'batteries.id', '=', 'test.battery_id')
//->where('test->athlete().gender', '=' $gender)
->where('battery_id', '=', $battery)
->get();
它在您添加性别位之前有效。我正在测试不同的语法,也许第二个$ q->必须出来? – louisav
你的运动员表是否有性别栏? – geckob
如果使用'gender'变量,则需要将其包含在函数闭包中。 – geckob