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