Laravel 一对多(反向)/属于 return null

Laravel One To Many (Inverse) / Belongs To return null

我用Laravel 8。我有 3 table。课程 table、UserCourse 和用户 table。我想获得用户课程。我用 tinker 试了一下:Course::find(1)->user_courses - 它工作正常并还给我 user_course.

UserCourse::find(1)->user_course - 问题就在这里,这将 return 我“null”

如何获取用户课程?

课程table

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

用户课程table

    Schema::create('user_courses', function (Blueprint $table) {
        $table->id();
        $table->foreignId('user_id')->constrained()->onDelete('cascade');
        $table->foreignId('course_id')->constrained()->onDelete('cascade');
        $table->timestamps();
    });

用户table

    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('email')->unique();
        $table->string('username')->unique();
        $table->string('password');
        $table->timestamp('updated_at')->nullable();
        $table->timestamp('created_at')->nullable();
    });

Course.php

class Course extends Model
{
use HasFactory;

protected $fillable = [
    'title',
];

public function user_courses()
{
    return $this->hasMany(UserCourse::class);
}
}

用户Course.php

class UserCourse extends Model
{
use HasFactory;

protected $fillable = [];


public function user_course()
{
    return $this->belongsTo(Course::class);
}
}

你的数据库结构使得课程和用户之间的关系是多对多关系,中间有一个枢轴table。

您需要做一些更正才能使其看起来符合 laravel 约定。

- 枢轴 table 名称应该是 course_user 没有主键

 Schema::create('course_user', function (Blueprint $table) {
        $table->foreignId('user_id')->constrained()->onDelete('cascade');
        $table->foreignId('course_id')->constrained()->onDelete('cascade');
        $table->timestamps();
    });

- 删除 UserCourse.php 模型,因为它是一个枢轴

- 定义User模型中的关系课程如下

User.php

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

- 在课程模型中定义关系用户如下

Course.php

public function users()
{
    return $this->belongsToMany(User::class);
}

现在要获得任何用户课程,只需运行User::find(1)->courses

获取属于相同用户的相同方法Course::find(1)->users

获取用户未参加的课程:

$userId = 1;
$courses = Course::whereDoesntHave('users', function($userQB) use($userId) {
    $userQB->where('id',$userId);
})->get();