微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 eloquent 在 Laravel 中仅获取一个用户数据?

如何解决如何使用 eloquent 在 Laravel 中仅获取一个用户数据?

我使用 Laravel 8。我想获取用户进程课程,但我获取所有用户进程。

在 User.PHP

  public function courses()
    {
        return $this->belongsToMany(Course::class);
    }

Course.PHP

public function progresses()
 {
    return $this->hasMany(Progress::class);
 }

Progress.PHP 为空。

课程表

Schema::create('courses',function (Blueprint $table) {
        $table->id();
        $table->string('title');
        ...
        $table->timestamps();
    });

进度表

    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;
}

这个回报:

enter image description here

但我只想要 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();

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。