我有这些表
Hotels:
id = auto increment
name_hotel = text
....
Rooms:
id = auto increment
id_room = auto increment (just in same hotel)
hotel_id = integer
...
在房间表中我有三列(id =自动增量,id_room =我想让这个列自动增加但只在1个酒店,每个酒店增加房间id_room将是1,2,3,4)
示例:
id id_room hotel_id
1 1 4
2 2 4
3 3 4
4 1 (start again) 5(new hotel)
5 4 4
6 2 5
可以在laravel模型中使用Eloquent
答案 0 :(得分:1)
好吧,如果您在插入数据时知道酒店ID,那么您可以将id_room
设置为该酒店最高ID房间的一个。
首先,从id_room
中删除自动增量。自动增量旨在与主键或ID应始终递增的行一起使用。尝试重置计数器永远不是一个好主意,据我所知,Laravel没有给你选择。但是通过移除auto_increment
,我们可以自己创建一个满足您需要的东西。
为此,我们可以使用Eloquent选择max(id_room) where hotel_id=?
:
$id = 4; // or whatever ID you are inserting
$current_id = DB::table('rooms')->where('hotel_id', $id)->max('id_room');
然后,只需在插入数据时向current_id添加一个
$row = DB::table('rooms')->insert(
['id_room' => $current_id + 1, 'hotel_id' => $id];
);