简体   繁体   English

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

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

i have two tables on mysql我在 mysql 上有两张桌子

Item Table项目表

Id ID item_name项目名 room_id room_id other column其他栏目
1 1 table桌子 1 1
2 2 book 2 2
3 3 clock 2 2

Room Table房间表

id ID room_name房间名
1 1 Teacher room教师室
2 2 class room class房

I have a case that one item can be in several rooms,我有一个案例,一件物品可以放在几个房间里,

I was asked for the data not to be duplicated as follows我被要求不重复数据如下

Id ID item_name项目名 room_id room_id other column其他栏目
1 1 table桌子 1 1
2 2 table桌子 2 2

how to store at one row column room_id has many value like this如何存储在一行列 room_id 有很多这样的值

Id ID item_name项目名 room_id room_id other column其他栏目
1 1 table桌子 1,2 1,2

I've done it using a string and then I extracted it using explode() but in mysql table I can't connect to the room table anymore我已经使用字符串完成了它,然后我使用explode() 将其提取但在mysql 表中我无法再连接到房间表

you can achieve that by using a pivot table您可以通过使用 pivot 表来实现

table: item_room

columns: item_id, room_id

models should look like this模型应该是这样的

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