【问题标题】:how to save many foreign key at one cell如何在一个单元格中保存多个外键
【发布时间】:2022-01-17 17:12:55
【问题描述】:

我在mysql上有两个表

项目表

Id item_name room_id other column
1 table 1
2 book 2
3 clock 2

房间桌

id room_name
1 Teacher room
2 class room

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

我被要求不要复制数据如下

Id item_name room_id other column
1 table 1
2 table 2

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

Id item_name room_id other column
1 table 1,2

我用一个字符串完成了它,然后我用explode()提取了它,但是在mysql表中我不能再连接到房间表了

【问题讨论】:

  • 不要在第二个表中使用item_name,而在第二个表中只使用id。因为您已经拥有第一个表中的 item_name。

标签: php mysql laravel eloquent laravel-8


【解决方案1】:

您可以通过使用数据透视表来实现这一点

  • 桌子:item_room
  • 列: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, querying relation, etc.
$room = Room::find(1);
foreach($room->items() as $items){
    //todo
}

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

【讨论】:

  • 不需要数据透视类。有一个数据透视表是必要的。
猜你喜欢
  • 2021-10-18
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 2021-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多