Laravel 5.3 eloquent 3 table join using models

泄露秘密 提交于 2019-12-24 12:20:05

问题


I read this post which helped, but need more guidance please.

I need a set of Results for a particular $batteryid (on Result) and a particular $age (on Test model) and a particular $gender (from Athlete). Each Test belongs to one athlete. Each test has many results.

Model Battery:

class Battery extends Model{
    public function results(){
        return $this->hasMany('App\Result');
    }    
}

Model 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');
    }    
}

Model Test:

class Test extends Model{
    public function athlete(){
        return $this->belongsTo('App\Athlete', 'athlete_id');
    }

    public function results(){
        return $this->hasMany('App\Result');
    }
}

I get the correct results with the following, but it's two queries:

$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();

I'd like to use model approach, but am completely stuck. test.age not recognised and not sure how to get the age from athlete model. My attempt:

            $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(); 

回答1:


You can use whereHas for the condition and with method for eager loading it.

    $results = Result::whereHas('test', function($q) use ($age) {
          $q->where('age', '=', $age);
          $q->whereHas('athlete', function ($q) {
              $q->where('gender', 'male');
          });

        })
        ->with('test')
        ->whereHas('battery', function($q) use($battery) {
            $q->where('battery_id', '=', $battery);
        })
        ->with('battery')
        ->get();


来源:https://stackoverflow.com/questions/42367415/laravel-5-3-eloquent-3-table-join-using-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!