Я использую Laravel 5.6 и пытаюсь отфильтровать отношения внутри моей User
модели. Пользователь может посещать курсы, для которых привязаны баллы.
Пользователи могут зарабатывать эти очки, посещая курсы. Это отношения BelongsToMany
.
Я пытался создать область действия в этой User
модели, которая включала бы только посещенные курсы в течение ряда лет.
/**
* Retrieves the courses which the user has attended
*/
public function attendedCourses()
{
return $this->belongsToMany(Course::class, 'course_attendees');
}
/**
* Searches the user model
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param array $years
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeAttendedCoursesInYears(Builder $builder, array $years)
{
# Filter on the years
$callback = function($q) use ($years) {
foreach ($years as $year) {
$q->year($year);
}
};
return $builder->with(['attendedCourses' => $callback]);
}
В моей Course
модели у меня есть область, которая фильтрует по году, в котором был курс.
public function scopeYear(Builder $query, int $year)
{
return $query->whereYear('end_date', $year);
}
С этой областью attendedCoursesInYears
я надеялся, что смогу затем подсчитать количество баллов для каждого пользователя, суммируя баллы курса, используя другие области действия в модели Course
.
public function scopeExternal(Builder $query, bool $flag = true)
{
$categoryIsExternal = function($query) use ($flag) {
$query->external($flag);
};
return $query->whereHas('category', $categoryIsExternal);
}
В моем CourseCategory
модале область видимости выглядит следующим образом:
/**
* Scope a query to only include external categories.
*
* @param \Illuminate\Database\Eloquent\Builder $query
*
* @param bool $flag
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeExternal(Builder $query, $flag = true)
{
return $query->where('type', '=', $flag ? 'Extern' : 'Intern');
}
Для расчета я попытался сделать что-то вроде этого.
# Retrieve all the active users
$users = User::all()->attendedCoursesInYears($years);
$test = $users->find(123);
# Calculate the points
$test->attendedCourses()->external(false)->sum('points');
Это, однако, вернуло общую сумму всех курсов.
Использование области, как я вижу, является единственным вариантом здесь. Я хочу создать пользовательские атрибуты из этих значений, используя подобные методы доступа. Это так, чтобы я мог легко отсортировать рассчитанные значения.
/**
* The users internal course points
*
* @param array $years The years to look for attended courses
*
* @return float
*/
public function getInternalPointsAttribute() : float
{
return $this->attendedCourses()->external(false)->sum('points');
}
Единственная проблема здесь - это фильтр года. Я надеялся, что смогу отфильтровать коллекцию User перед вызовом метода доступа, как в моем первом примере.
Что я здесь не так делаю?
В настоящее время я использую этот обходной путь. Это выглядит так плохо, потому что я повторяю так много кода.
/**
* @param \Illuminate\Database\Eloquent\Builder $builder
*
* @param array $years
*
* @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder
*/
public function scopeWithPoints(Builder $builder, array $years = [])
{
# Join all columns
$builder->join('user_roles', 'users.role_id', '=', 'user_roles.id')
->leftJoin('course_attendees', 'users.id', '=', 'course_attendees.user_id');
# Join the course table for the years
$builder->leftJoin('courses', function(JoinClause $join) use ($years) {
# Join the courses table with year filters
$join->on('course_attendees.course_id', '=', 'courses.id');
# Apply the filters if available
!empty($years) and $join->whereIn(DB::raw('YEAR(courses.end_date)'), $years);
});
# Select the columns
$builder->select('users.*')->groupBy('users.id');
# Sums
$internalPoints = 'SUM(courses.points_internal)';
$externalPoints = 'SUM(courses.points_external)';
# Select the points
$builder->selectRaw('COALESCE(' . $internalPoints . ', 0) as internal_points');
$builder->selectRaw('COALESCE(' . $externalPoints . ', 0) as external_points');
$builder->selectRaw('COALESCE(' . $internalPoints . ' + ' . $externalPoints . ', 0) as total_points');
# Sum up the course points
return $builder;
}
Миграцию для моей структуры базы данных можно найти здесь.
Schema::create('course_attendees', function(Blueprint $table)
{
$table->integer('id', true);
$table->integer('user_id')->index('course_attendees_users_id_fk');
$table->integer('course_id')->index('course_attendees_courses_id_fk');
$table->boolean('mijnafas');
});
Schema::create('courses', function(Blueprint $table)
{
$table->integer('id', true);
$table->string('title');
$table->string('subject');
$table->string('presenter');
$table->date('start_date')->nullable()->comment('Set to not null later');
$table->date('end_date')->nullable();
$table->decimal('points', 4)->nullable();
$table->string('location');
$table->timestamps();
});
Schema::create('users', function(Blueprint $table)
{
$table->integer('id', true);
$table->string('first_name')->nullable();
$table->string('last_name')->nullable();
$table->timestamps();
});
Schema::table('course_attendees', function(Blueprint $table)
{
$table->foreign('course_id', 'course_attendees_courses_id_fk')->references('id')->on('courses')->onUpdate('RESTRICT')->onDelete('RESTRICT');
$table->foreign('user_id', 'course_attendees_users_id_fk')->references('id')->on('users')->onUpdate('RESTRICT')->onDelete('RESTRICT');
});
Я заметил, что при простом вызове $test->attendedCourses
он возвращает отфильтрованную коллекцию. Проблема в том, что я не могу применить области к этому.
Вопросы
- Как получилось, что он не будет суммировать отфильтрованную коллекцию?
- Как сделать так, чтобы он соответствующим образом отфильтровал эту коллекцию?