gorm 中left join的使用
使用mysql语句执行时可以执行成功,但是使用go语言编程保存到struct中时出现问题。
代码如下:
sflog.Debug("QueryByTaskId ", id)
type Data struct {
TaskId int64 `json:"taskId"`
VehicleName string `json:"vehicleName"`
VehicleElec float64 `json:"vehicleElec"`
VehicleNumber string `json:"vehicleNumber"`
VehicleLocation int64 `json:"vehicleLocation"`
VehicleStatus int `json:"vehicleStatus"`
}
var datas []Data
joinQuery := mu.DB.Table("job j").Select("j.business_id AS taskId, a.name AS vehicleName, s.battery AS vehicleElec, j.agv_serial_no AS vehicleNumber, s.node_id AS vehicleLocation, s.state AS vehicleStatus").
Joins("LEFT join agv a on a.serial_no = j.agv_serial_no").
Joins("LEFT JOIN agv_state s on s.business_id = a.agv_state_id").
Where("j.business_id=?", id)
if err = joinQuery.Debug().Find(&datas).Error; err != nil {
sflog.Errorf("query job table err:%v ", err.Error())
}
sflog.Debug("datas: ", datas)
执行语句后datas是null的。后面改为这个语句,执行ok
joinQuery := mu.DB.Table("job j").Select("j.business_id AS task_id, a.name AS vehicle_name, s.battery AS vehicle_elec, j.agv_serial_no AS vehicle_number, s.node_id AS vehicle_location, s.state AS vehicle_status").
Joins("LEFT join agv a on a.serial_no = j.agv_serial_no").
Joins("LEFT JOIN agv_state s on s.business_id = a.agv_state_id").
Where("j.business_id=?", id)