我有这些表
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 中实现
最佳答案
好吧,如果您在插入数据时知道酒店 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];
);
关于php - 使用两列自动递增(laravel 4.1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32959359/