[英]how to join a laravel relation
I want to write a sort class for spatie query builder but my problem is I have 3 models hotel
room
and discount
so now hotel has many rooms and rooms has many discounts I want to sort the hotels by the lowest discount available on rooms so now here is the query I tried note that $query
is loading all the hotels:我想为 spatie 查询生成器编写一个排序 class 但我的问题是我有 3 个模型
hotel
room
和discount
所以现在酒店有很多房间和房间有很多折扣我想按房间上可用的最低折扣对酒店进行排序所以现在在这里是我尝试过的查询,请注意$query
正在加载所有酒店:
$data = $query->with('accommodationRoom')
->join('discounts','accommodation_rooms.id','=','discounts.accommodation_room_id')
->get();
but I get this error:但我收到此错误:
message: "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'accommodation_rooms.id' in 'on clause' (SQL: select * from
accommodations
inner joindiscounts
onaccommodation_rooms
.id
=discounts
.accommodation_room_id
where exists (select * fromaccommodation_rooms
whereaccommodations
.id
=accommodation_rooms
.accommodation_id
andbed_count
= 5))",消息:“SQLSTATE [42S22]:未找到列:1054 'on 子句'中的未知列 'accommodation_rooms.id'(SQL:select * 来自
accommodations
内部加入的accommodation_rooms
discounts
。id =discounts
。accommodation_room_id
房间id
存在的地方(从accommodation_rooms
中选择 *)其中accommodations
bed_count
=accommodation_rooms
.accommodation_id
id
和床数 = 5))",
its because I am loading a relation to a join but that does not recognizing the filed.这是因为我正在加载与联接的关系,但不识别该文件。
Use multiple join statements..使用多个连接语句..
$data = DB::table('accommodation_rooms')
->join('hotels','accommodation_rooms.id','=','hotels.room_id') // replace room_id with your column name
->join('discounts','accommodation_rooms.id','=','discounts.accommodation_room_id')
->select('accommodation_rooms.*','hotels.*','discounts.*')
->get();
Add Relation in Model files.在 Model 文件中添加关系。
Hotel Model酒店 Model
Class Hotel{
public function room()
{
return $this->hasMany(Room::class,'hotel_id','id');
}
}
Room Model房间 Model
Class Room{
public function discount()
{
return $this->hasMany(Discount::class,'room_id','id');
}
}
Record Fetch Query记录提取查询
$data = Hotel::with('room', 'room.discount')->orderBy('room.discount.value', 'ASC')->get();
Change your model and field name in the above code.更改上述代码中的 model 和字段名称。
You should join with accommodationRoom
too.您也应该加入
accommodationRoom
。
You can even join to multiple tables in a single query:您甚至可以在单个查询中加入多个表:
$data = $query->join('accommodation_rooms','hotels.id','=','accommodation_rooms.hotel_id')
->join('discounts','accommodation_rooms.id','=','discounts.accommodation_room_id')
->select('hotels.*', 'discounts.*')
->orderBy('discounts.value')
->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.