如何用eloquent只获取Laravel中的一个用户数据?
How to get just one user data in Laravel with eloquent?
我用Laravel 8。我想获得用户进程课程,但我获得了所有用户进程。
在User.php
public function courses()
{
return $this->belongsToMany(Course::class);
}
Course.php
public function progresses()
{
return $this->hasMany(Progress::class);
}
Progress.php 为空。
课程table
Schema::create('courses', function (Blueprint $table) {
$table->id();
$table->string('title');
...
$table->timestamps();
});
进度table
Schema::create('progress', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->foreignId('course_id')->constrained()->onDelete('cascade');
$table->integer('percent');
$table->timestamps();
});
课程控制器
public function index()
{
$userCourses = User::where('id', 1)->with('courses.progresses')->first();
return $userCourses;
}
还有这个return:
但我只想要 user_id = 1.
的过程
With()
方法可以使用特定的数组注解来限制急切加载。 documentation.
中也对此进行了描述
$userId = 1;
$userCourses = User::where('id', $userId)
->with(
[
'courses.progresses' => function ($query) use ($userId) {
$query->where('user_id', $userId)
},
]
)->first();
我用Laravel 8。我想获得用户进程课程,但我获得了所有用户进程。
在User.php
public function courses()
{
return $this->belongsToMany(Course::class);
}
Course.php
public function progresses()
{
return $this->hasMany(Progress::class);
}
Progress.php 为空。
课程table
Schema::create('courses', function (Blueprint $table) {
$table->id();
$table->string('title');
...
$table->timestamps();
});
进度table
Schema::create('progress', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->foreignId('course_id')->constrained()->onDelete('cascade');
$table->integer('percent');
$table->timestamps();
});
课程控制器
public function index()
{
$userCourses = User::where('id', 1)->with('courses.progresses')->first();
return $userCourses;
}
还有这个return:
但我只想要 user_id = 1.
的过程With()
方法可以使用特定的数组注解来限制急切加载。 documentation.
$userId = 1;
$userCourses = User::where('id', $userId)
->with(
[
'courses.progresses' => function ($query) use ($userId) {
$query->where('user_id', $userId)
},
]
)->first();