我在用户和课程之间有一个多对多关系,其中包含一个数据透视表 Users_Courses,其中包含 isComplete 值,但我似乎无法在不循环每个用户并获取他们的课程的情况下检索 isComplete 值然后循环每个课程获取枢轴数据。
我发现的所有示例都是将 isComplete 值映射到带有循环的课程,但这似乎对程序造成了极大的负担,而且我并没有真正发现它有吸引力,这就是为什么我要制作我的自己的问题在这里。如果我还没有看到这个问题的答案,请在下面链接它,因为我似乎找不到它。
此外,我正在使用 Laravel-9 和 MySQL。
我现在检索的数据结构如下所示:
"data": [
{
"id": 2,
"fname": "name",
"lname": "last name",
"email": "mail@mail.com",
"courses": [
{
"id": 1,
"name": "test_course_1",
"description": "this is a test course for testing"
},
{
"id": 2,
"name": "test_course_2",
"description": "this is also a test course"
},
{
"id": 3,
"name": "test_course_3",
"description": "this course is a test course"
}
]
}
]
我正在寻找一种方法来检索枢轴值 isComplete 与 Eloquent 并获取课程本身的数据,就像这样或类似的东西。
换句话说,我想通过数据透视表值 isComplete 来检查用户是否完成了课程,如下例所示。< /p>
"data": [
{
"id": 2,
"fname": "name",
"lname": "last name",
"email": "mail@mail.com",
"courses": [
{
"id": 1,
"name": "test_course_1",
"description": "this is a test course for testing",
"isComplete": 1
},
{
"id": 2,
"name": "test_course_2",
"description": "this is also a test course",
"isComplete": 0
},
{
"id": 3,
"name": "test_course_3",
"description": "this course is a test course",
"isComplete": 0
}
]
}
]
我现在的代码如下所示:
class User extends Authenticatable
{
public function courses()
{
return $this->belongsToMany(Course::class, 'user_courses')
->withPivot('isCompleted');
}
}
class Course extends Model
{
public function users()
{
return $this->belongsToMany(User::class, 'user_courses')
->withPivot('isCompleted');
}
}
class UserController extends Controller
{
public function getUsersById(int $user_id)
{
try {
$users = User::where('id', $user_id)
->with('courses')
->get();
return response()->json([
'success' => true,
'data' => $users
]);
} catch (Throwable $th) {
return response()->json([
'success' => false,
'data' => null,
'message' => $th,
]);
}
}
}
我知道它在代码中称为 isCompleted ,但在数据库中也这么叫。这是一个尚未修复的打字错误:D
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
换句话说,我想通过数据透视表值 isComplete 检查用户是否已完成课程,如下例所示。
您是否在文档中阅读了有关使用数据透视表列进行过滤的信息:https://laravel.com/docs/9.x/eloquent-relationships#filtering-queries-via-intermediate-table-columns
如果您只需要完成的课程,您可以将关系称为
$users = User::where('id', $user_id) ->with(['courses' => function($query) { $query->wherePivot('isCompleted', 1); // use quotes if its datatype is enum in database. }]) ->get();或者您可以为模型中的已完成、未完成建立自定义关系。
class User extends Authenticatable { public function courses() { return $this->belongsToMany(Course::class, 'user_courses') ->withPivot('isCompleted'); } public function completedCourses() { $this->courses()->wherePivot('isCompleted', 1); } public function InCompleteCourses() { $this->courses()->wherePivot('isCompleted', 0); } }在用户控制器中,您可以将它们称为
$users = User::where('id', $user_id) ->with('completedCourses') ->get();