php - 雄辩的多对多关系总是空的
问题描述
我知道这个问题被问了很多,但所有答案似乎都对我不起作用——或者至少我发现的问题是关于数据透视表的。
我有一个由数据透视表“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 个约会......奇怪。
解决方案
尽管您的表名和列名似乎与 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');
}
}
推荐阅读
- angularjs - 有没有办法在使用 angularjs 渲染时间后添加时区?
- angular - Angular 6 - 全日历
- c++ - 如何使用 QTcp 使用标准化的请求响应事务?
- javascript - 如何在javascript中将文件移动到驱动器api v3中的垃圾箱?
- google-sheets - 如何制作一个生成动态谷歌表格的烧瓶网站
- python - TypeError: '>' 在'float' 和'str' 的实例之间不支持
- c# - 如何从 Xamarin Forms 代码打开或访问 Android 片段中的数据?
- javascript - 一旦条件为真,如何在 JavaScript 中中断 if/else 语句
- c# - C# 将字符串解析为具有特定时区的 DateTime
- onedrive - OneDrive 选择器未加载