我用下面的方法从几个表中检索数据:
$data = Accommodation::join("hotels", "accommodations.hotel_id", "=", "hotels.id")
->join("room_types", "accommodations.room_type", "=", "room_types.id")
->join("country", "accommodations.country_id", "=", "country.id")
->join("accommodation_accreditation", "accommodations.id", "=", "accommodation_accreditation.accommodation_id")
->join("accreditation", 'accreditation.id', "=", "accommodation_accreditation.accreditation_id")
->select('hotels.name as Hotel' ,'room_types.type as Room', 'price_per_night as Price per Night', 'check_in as Check In', 'check_out as Check Out', 'nights as Nights', 'sub_total as Sub Total', 'country.name as Country', 'accreditation.full_name as Occupants')
->get()->toArray();我会为房间里的每个住客安排一排。
Room Price per Night Check In Check Out Nights Sub Total Country Occupants
---------------------- ----------------- ------------ ------------ -------- ----------- --------- -------------------
Twin/Double standart 160 2019-04-10 2019-04-15 5 800 UKR Vlad Timochenko
Twin/Double standart 160 2019-04-10 2019-04-15 5 800 UKR Selena Viachenko 我需要将居住者的名字连接起来,并将它们放在一行中,如下所示:
Room Price per Night Check In Check Out Nights Sub Total Country Occupants
---------------------- ----------------- ------------ ------------ -------- ----------- --------- ------------------------------------
Twin/Double standart 160 2019-04-10 2019-04-15 5 800 UKR Vlada Nikolchenko, Olena Diachenko 以下是我对相关表的模式

希望一切都清楚了。如果你能帮上忙的话就太好了。
发布于 2019-03-11 22:24:37
老实说,我从不同的地方找到了我的案例的完整解决方案。
正如sam建议的那样,我使用了GROUP_CONCAT。我的代码看起来像这样:
$data = Accommodation::join("hotels", "accommodations.hotel_id", "=", "hotels.id")
->join("room_types", "accommodations.room_type", "=", "room_types.id")
->join("country", "accommodations.country_id", "=", "country.id")
->join("accommodation_accreditation", "accommodations.id", "=", "accommodation_accreditation.accommodation_id")
->join("accreditation", 'accreditation.id', "=", "accommodation_accreditation.accreditation_id")
->select('hotels.name as Hotel' ,'room_types.type as Room', 'price_per_night as Price per Night', 'check_in as Check In', 'check_out as Check Out', 'nights as Nights', 'sub_total as Sub Total', 'country.name as Country', DB:raw("GROUP_CONCAT('accreditation.full_name SEPRATOR ',') as `Occupants`"))
->groupBy('accommodation.id')
->get()->toArray();我不得不提防的另一件事是对占有者标签使用反引号,否则分隔符不能正常工作。
还有其他类似的线程,所以这是重复的。
Group_concat - laravel eloquent how to use GROUP_CONCAT in laravel
https://stackoverflow.com/questions/55090064
复制相似问题