首页 > 解决方案 > 雄辩的多对多关系总是空的

问题描述

我知道这个问题被问了很多,但所有答案似乎都对我不起作用——或者至少我发现的问题是关于数据透视表的。

我有一个由数据透视表“apointment_user”连接的多对多关系(用户 - 约会),请参阅下面的迁移。

Schema::create('appointment_user', function (Blueprint $table) {
   $table->unsignedInteger('user_id')->nullable();
   $table->foreign('user_id')->references('id')->on('users');
   $table->unsignedInteger('appointment_id')->nullable();
   $table->foreign('appointment_id')->references('id')->on('appointments');
   $table->primary(['user_id','appointment_id']);
   $table->timestamps();
});
Schema::create('appointments', function (Blueprint $table) {
  $table->increments('id');
  $table->string('title');
  $table->dateTime('date');
  $table->string('location');
  $table->dateTime('departure');
  $table->timestamps();
});
Schema::create('users', function (Blueprint $table) {
  $table->increments('id');
  $table->string('name');
  $table->string('email')->unique();
  $table->string('password');
  $table->date('last_login')->nullable();
  $table->rememberToken();
  $table->timestamps();
  $table->softDeletes();
});

class User extends Model {
  protected $with = ['appointments'];
  public function appointments() : BelongsToMany {
    return $this->belongsToMany(Appointment::class);
  }
}

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

我有一个用户的 ID1和大约 10 个约会,我确实将其附加到播种器中的关系。正如预期的那样,数据透视表有 10 条记录(用户 ID 始终为1)。

但是,如果我使用 转储我的 User 对象dd(User::find(1)),则该关系始终是一个空集合。但是,1:n 关系(角色之间的关系很好)。

有人看到我错过了什么吗?任何帮助表示赞赏。非常感谢和亲切的问候


编辑

我只是尝试了其他类型的倾倒。我只是将我的用户对象作为 JSON 响应返回,并且该关系充满了 10 个约会......奇怪。

标签: phplaraveleloquentormmany-to-many

解决方案


尽管您的表名和列名似乎与 Laravel 猜测的一样,但您是否尝试过明确名称?

class User extends Model {
  protected $with = ['appointments'];
  public function appointments() : BelongsToMany {
    return $this->belongsToMany(Appointment::class, 'appointment_user', 'user_id', 'appointment_id');
  }
}

class Appointment extends Model {
  public function users() : BelongsToMany {
    return $this->belongsToMany(User::class, 'appointment_user', 'appointment_id', 'user_id');
  }
}

推荐阅读