【发布时间】:2021-05-16 13:12:24
【问题描述】:
我不确定如何最好地构建我的表,以便存储和查询高效且简单..
这就是我所拥有的:
- rooms 表 - 包含 10 多种不同的房间类型(厨房、休息室等),(具有唯一 ID)
- properties_rooms 查找表 - 属性 ID 和 Room_id
- properties 表 - 包含许多不同的属性(具有唯一 ID)
除了上述之外,我还需要能够为每个属性/房间组合捕获特定的注释和级别属性,例如:
- (属性 ID - '1')-> 来自属性表
- (属性名称 -'Sunny House')-> 来自属性表
- (房间 ID - '2')-> 来自 properties_rooms 查找
- (房间名称 - '卧室')-> 来自房间表
- (级别 - “一楼”)-> 什么桌子??
- (注 - “双床”)-> 什么桌子??
上面的 Level 和 Note 是特定于属性和房间类型的组合,所以在查找中似乎有意义?
我有以下方案设置:
属性
Schema::create('properties', function (Blueprint $table) {
$table->id();
.....
房间和属性_房间
Schema::create('rooms', function (Blueprint $table) {
$table->id();
$table->string('name')->unique();
$table->timestamps();
});
Schema::create('properties_room', function (Blueprint $table) {
$table->id();
$table->foreignId('properties_id')->constrained('properties')->onDelete('cascade');
$table->foreignId('room_id')->constrained('rooms')->onDelete('cascade');
$table->string('level');
$table->string('note');
$table->timestamps();
$table->unique(['properties_id','room_id']);
});
模型
Rooms
public function properties()
{
return $this->belongsToMany(Properties::class);
}
Properties
public function rooms()
{
return $this->belongsToMany(Room::class);
}
“级别”和“注释”字段在查找文件中似乎是正确的。但我不确定这是否正确,或者如何访问它们?
在我的刀片视图中,这些都有效:
- {{ $properties }} - 属性表属性
- {{ $properties->rooms }} - 房间表属性
但是通过“房间”属性,我看不到查找文件中保存的信息,这显然是使用过的?
【问题讨论】:
-
一个
Room可以属于多个Properties? -
withPivot()可以帮助您从联结表中获取更多详细信息 -
谢谢哈立德。我认为 withPivot() 是我需要的。 Unflux,是的,房间只是一种类型。因此该类型可能属于许多属性。该房间的具体情况、级别和属性,然后在联结/查找/数据透视表中捕获..
标签: php laravel database-design eloquent