首页 > 解决方案 > 为什么 Laravel 无法创建模型关系?

问题描述

我正在尝试在 laravel 中的模型之间建立关系,但由于某种原因它似乎失败了。

class User extends Authenticatable
{
    use HasFactory, Notifiable;
    protected $table = 'users';
    protected $fillable = [
        'name',
        'email',
        'password',
        'userType'
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    //classes created by user;
    public function classes() {
        return $this->hasMany(userOwnedClass::class, 'ownerId');
    }
}
class userOwnedClass extends Model { 
    protected $table = 'classes'; 
    protected $fillable = ['name', 'archived', 'ownerId']; 
    public $timestamps = false;

    public function owner() {
        return $this->belongsTo(User::class, 'ownerId');
    }
}

的数据库结构users如下所示:

class Users extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->enum('userType', ['student', 'teacher']);
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

类的数据库结构如下所示:

class Classes extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('classes', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->boolean('archived')->default(0);
            $table->integer('ownerId')->unsigned();
            $table->foreign('ownerId')->references('id')->on('users');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('classes');
    }
}

每当我尝试owner()在 的实例上对方法进行分类时userOwnedClass,我都会收到一个Illuminate\Database\Eloquent\Relations\BelongsTo对象而不是 User 的实例。任何人都可以识别错误吗?

标签: phplaravel

解决方案


您应该将owner其称为属性而不是方法。

$userOwnedClass->owner;

当你调用owner()方法时,你会得到一个 eloquent 关系的实例来对该模型执行额外的查询。

如果调用函数 owner(),可以通过以下方式获取所有者的 id

$userOwnedClass->owner()->id;

推荐阅读