Laravel 从数据中心获取每天的练习 table

Laravel get exercises by day from pivot table

我正在尝试查询一个数据透视表 table 以显示一天有多少练习,但是这有问题。

我需要在星期一或任何一天完成所有练习。

我有三个 table:routinesexercisesexercise_routine

routines     exercise_routine  exercise
--------     ----------------  --------
id           id                id
name         routine_id        name
description  exercise_id       description
user_id      week_day_id
             sets
             reps

我想得到 week_day_id 的所有练习,希望你能理解我的问题。

我在 Whosebug 上尝试了其他人的这些示例,但它不起作用。

Exercise::whereHas('routines', function($q) {
    $q->where('routines.week_day_id', 1);
})
->get();
return \DB::table('exercises')
->join('exercise_routine', 'exercise_routine.exercise_id', '=', 'exercises.id')
->where('exercise_routine', 1)
->get();
dd( DB::table('exercises')
->where('exercises.id', '=', 1)
->select('exercises.id'));
// Routine Model
public function exercises()
{
    return $this->belongsToMany('App\Models\Exercise');
}
// ExerciseModel
public function routines()
{
    return $this->belongsToMany('App\Models\Routine')->as('plan')->withPivot('sets', 'reps', 'week_day_id')->withTimestamps();
}
// Controller
public function show(WeekDay $weekday)
{
    Exercise::whereHas('routines', function($q, $weekday) {
        $q->where('routines.week_day_id', $weekday);
    })
    ->get();
}
// api routes
Route::group(['prefix' => '/{weekday}/exercises'], function () {
    Route::get('/', 'WeekDayExerciseController@show')->middleware('auth:api');
});

我希望在星期一之前完成所有练习,例如:

{
    "id": 236,
    "name": "Upright Row (Barbell)",
    "description": "Description for Upright Row (Barbell)"
},
{
    "id": 237,
    "name": "Upright Row (Cable)",
    "description": "Description for Upright Row (Cable)"
},
{
    "id": 238,
    "name": "Upright Row (Dumbbell)",
    "description": "Description for Upright Row (Dumbbell)"
},

在您的 Controller 中,您的闭包有一个小错误

// Controller
public function show(WeekDay $weekday)
{
    Exercise::whereHas('routines', function($q) use ($weekday) {
        $q->where('week_day_id', $weekday->id);
    })
    ->get();
}

你错了

Exercise::whereHas('routines', function($q) {
    $q->where('routines.week_day_id', 1);
})
->get();

因为 week_day_id 列不在 routines table,

您需要以这种方式使用wherePivot方法查询枢轴table

Exercise::whereHas('routines', function($q) {
    $q->wherePivot('week_day_id', 1);
})
->get();

参见:https://laravel.com/docs/master/eloquent-relationships#many-to-many