You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 10中如何利用belongsToMany关联查询用户已购课程?

问题:Laravel 10 中在用户仪表盘展示用户已购买课程

需求

开发基于Laravel 10的课程网站,需在用户仪表盘页面展示当前用户已购买的课程,供用户开始或继续学习。

数据库表结构

courses表

Schema::create('courses', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->string('subtitle');
    $table->text('description');
    $table->enum('status',[Course::BORRADOR,Course::REVISION,Course::PUBLICADO])->default(Course::BORRADOR);
    $table->string('slug');
    $table->unsignedBigInteger('user_id');
    $table->unsignedBigInteger('level_id')->nullable();
    $table->unsignedBigInteger('category_id')->nullable();
    $table->unsignedBigInteger('price_id')->nullable();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->foreign('level_id')->references('id')->on('levels')->onDelete('set null');
    $table->foreign('category_id')->references('id')->on('categories')->onDelete('set null');
    $table->foreign('price_id')->references('id')->on('prices')->onDelete('set null');
    $table->timestamps();
});

users表

public function up(): void
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->foreignId('current_team_id')->nullable();
        $table->string('profile_photo_path', 2048)->nullable();
        $table->timestamps();
    });
}

course_user中间表(多对多关联表)

public function up(): void
{
    Schema::create('course_user', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('course_id');
        $table->unsignedBigInteger('user_id');
        $table->foreign('course_id')->references('id')->on('courses')->onDelete('cascade');
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->timestamps();
    });
}

模型多对多关联定义

User.php 模型

public function courses_enrolled(){
    return $this->belongsToMany('App\Models\Course');
}

Course.php 模型

public function students(){
    return $this->belongsToMany('App\Models\User');
}

解决方案:使用Livewire组件实现

此前尝试多种查询方式未得到预期结果,最终通过将逻辑迁移至Livewire组件完成功能,代码如下:

Livewire组件代码

class UserDashboard extends Component
{
    public $user;

    public function mount(User $user){
        $this->user = $user;
    }

    public function render()
    {
        // 修正变量名语义化,原代码$users为笔误
        $courses = $this->user->courses_enrolled()->paginate(8);

        return view('livewire.user-dashboard', compact('courses'));
    }
}

对应视图示例(livewire/user-dashboard.blade.php)

<div class="dashboard-courses">
    <h2>我的课程</h2>
    <div class="row">
        @foreach($courses as $course)
            <div class="col-md-3 mb-4">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">{{ $course->title }}</h5>
                        <p class="card-text">{{ $course->subtitle }}</p>
                        <a href="/courses/{{ $course->slug }}" class="btn btn-primary">开始/继续学习</a>
                    </div>
                </div>
            </div>
        @endforeach
    </div>

    {{ $courses->links() }}
</div>

功能现已正常运行。

内容的提问来源于stack exchange,提问作者Juan Rincón

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 07:45:56