![](/img/trans.png)
[英]How to get one->many relationship with a foreign key in laravel 5.2?
[英]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.