简体   繁体   中英

how to save many foreign key at one cell

i have two tables on mysql

Item Table

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

Room Table

id room_name
1 Teacher room
2 class room

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 item_name room_id other column
1 table 1
2 table 2

how to store at one row column room_id has many value like this

Id item_name room_id other column
1 table 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

you can achieve that by using a pivot table

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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