【发布时间】:2019-08-09 16:35:26
【问题描述】:
我知道这个问题被问了很多,但所有答案似乎都不适用于我 - 或者至少我发现的问题是关于数据透视表的。
我有一个由数据透视表“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);
}
}
我有一个 ID 为 1 的用户和大约 10 个约会,我确实将其附加到播种器中的关系中。数据透视表有 10 条记录,符合预期(用户 ID 始终为 1)。
但是,如果我使用dd(User::find(1)) 转储我的用户对象,则关系始终是一个空集合。但是,1:n 关系(角色之间的关系很好)。
有人看到我错过了什么吗?任何帮助表示赞赏。 非常感谢和亲切的问候
编辑
我只是尝试了其他类型的倾倒。我只是简单地将我的用户对象作为 JSON 响应返回,并且该关系充满了 10 个约会......奇怪。
【问题讨论】:
-
你应该让 Laravel 自动定义外键,而不是强制它们。另外,我不明白从 BelongsToMany 继承的意义:
public function users() : BelongsToMany。在我看来,您的手动方法使 Laravel 省略了关键功能,并没有为您设置关系。 -
@JCode 使用
public function name(): someType只是强制/指定返回的元素与someType类型/类匹配(例如string或User)。检查this example。 -
另一方面,@PaddaelsM,我不明白你在问什么,看来你已经解决了(?)。
-
@HCK 它也已过时,可能是他问题的根源。
public function users() { return $this->belongsToMany('App\User') }就足够了。 -
@JCode 根本没有。实际上是一个 PHP
7.0+功能。检查this list。这应该对他的问题没有任何影响。我们没有关于他如何提出查询或如何打印出来的更多信息。似乎已经解决了他的问题
标签: php laravel eloquent orm many-to-many