繁体   English   中英

如何在一个单元格中保存多个外键

[英]how to save many foreign key at one cell

我在 mysql 上有两张桌子

项目表

ID 项目名 room_id 其他栏目
1 桌子 1
2 2
3 2

房间表

ID 房间名
1 教师室
2 class房

我有一个案例,一件物品可以放在几个房间里,

我被要求不重复数据如下

ID 项目名 room_id 其他栏目
1 桌子 1
2 桌子 2

如何存储在一行列 room_id 有很多这样的值

ID 项目名 room_id 其他栏目
1 桌子 1,2

我已经使用字符串完成了它,然后我使用explode() 将其提取但在mysql 表中我无法再连接到房间表

您可以通过使用 pivot 表来实现

table: item_room

columns: item_id, room_id

模型应该是这样的

namespace App\Models;

class Item extends Model
{
    public function rooms()
    {
        return $this->belongsToMany(Room::class)->using(ItemRoom::class);
    }
}

namespace App\Models;

class Room extends Model
{
    public function items()
    {
        return $this->belongsToMany(Item::class)->using(ItemRoom::class);
    }
}

namespace App\Models;

class ItemRoom extends Pivot
{
    
}

# you can get data using eager loading, quering relation, etc.
$room = Room::find(1);
foreach($room->items() as $items){
    //todo
}

$item = Item::find(1);
foreach($item->rooms() as $items){
   //todo
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM