jeudi 7 novembre 2019

Query by a model function result in Laravel

I'm sure this should be simple but I can't quite get it. This is Laravel 5.4

I have a 3 models, Profile, Assessment and Responses. Each Profile has many Assessments, each Assessment has Many Responses.

I want to be able to get the Profiles which have a Latest Assessment where the total score of 0; I would assume I can somehow use my Model functions (latestAssessment() and total_points()) in an Eloquent query. Something like:

$noscore_profiles = \App\Profile::where('latestAssessment', function($query) {
        $query->where(total_points(), '=', 0);
    })->paginate(2, ['*'], 'noscore_profiles');

I have tried numerous ways of doing this and just can't get my head around it.

PROFILE:

class Profile extends Model
{
    protected $fillable = ['firstname', 'surname', 'gender', 'height', 'telephone', 'extension', 'start_date', 'yearly_reminder_sent'];

public function user() {
    return $this->belongsto('App\User');
}

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

public function latestAssessment() {
    return $this->hasOne('App\Assessment')->latest();
}

public function responses() {
    return $this->hasManyThrough('App\Response', 'App\Assessment');
}

public function total_points() {
    $total_points = 0;
    foreach($this->responses as $response) {
        $total_points += $response->answer->points;
    }
    return $total_points;
}
}

ASSESSMENT

class Assessment extends Model
{

protected $fillable = ['profile_id', 'start_date', 'completion_date', 'completion_status'];

public function profile()
{
    return $this->belongsTo('App\Profile');
}

public function review()
{
    return $this->hasOne('App\Review');
}

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

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

public function total_points() {
    $total_points = 0;
    foreach($this->responses as $response) {
        $total_points += $response->answer->points;
    }
    return $total_points;
}
}


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire