Anthony Ma
07/08/2022, 8:52 PMCREATE TABLE `iot_device` (
`id` varchar(255) NOT NULL PRIMARY KEY,
`type` varchar(255) NOT NULL,
`location` varchar(255) DEFAULT NULL
);
CREATE TABLE `iot_device_status` (
`id` int(10) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
`device` varchar(255) NOT NULL,
`lost` tinyint(1) DEFAULT 0,
`created_at` datetime(6) DEFAULT current_timestamp(6)
);
Since iot_device_status
stores current and historic statuses from every iot_device
, I use this SQL script to retrieve the current status from every unique device:
SELECT *
FROM iot_device_status s
JOIN (SELECT device, MAX(created_at) AS max_date FROM iot_device_status GROUP BY device) sm
ON s.created_at = sm.max_date
AND s.device = sm.device;
In Objection JS, I can define this relationship in my entity and then referenced when needed:
export default class IOTDevice extends BaseEntity {
...
static relationMappings = () => ({
statusRelationship: {
relation: Model.HasOneRelation,
modelClass: IOTDeviceStatus,
join: {
from: "iot_device.id",
to: "iot_device_status.device",
},
modify: function (builder) {
builder
.alias("s")
.join(
IOTDeviceStatus.raw(
"(SELECT device, MAX(created_at) AS max_date FROM iot_device_status GROUP BY device) AS sm"
),
function () {
this.on("s.created_at", "=", "sm.max_date").andOn(
"s.device",
"=",
"sm.device"
);
}
);
},
},
});
}
const res = await IOTDevice.query().withGraphJoined("statusRelationship"); // returns the most recent status of each device
but as far as I can tell, there's no support for this kind of modification to relation. I would have to implement this outside of the client. Am I just overlooking something or am I correct in that prisma has no support for something like this?Austin
07/08/2022, 9:22 PMAnthony Ma
07/08/2022, 9:58 PM