如何使用Loopback Include关联过滤指定部门的请假详情数据?
Got it, let's tackle this problem step by step. You want to fetch leave_details records where the associated employee belongs to department ID x, right? Here's how to make it work with your existing model setup:
1. 先完善Employee模型的关联配置(如果还没做的话)
You mentioned employee has a department_id property, but we need to formalize the relation between employee and department to enable nested filtering. Add this to your employee.json under the relations section:
"relations": { "department": { "type": "belongsTo", "model": "department", "foreignKey": "department_id" } }
This tells your ORM that each employee belongs to one department, linked via the department_id foreign key.
2. 编写查询代码
Depending on your framework (this looks like LoopBack, given the JSON model config), here's how to fetch the target leave_details records:
Option 1: Include Employee + Filter by Department ID
This approach explicitly includes the associated employee and filters based on their department ID:
// LoopBack 3 example LeaveDetails.find({ include: { relation: 'employee', scope: { where: { department_id: x } } } }, (err, leaveRecords) => { if (err) { // Handle error return; } // Use your leave records here });
// LoopBack 4 example (using repositories) const leaveRecords = await leaveDetailsRepository.find({ include: [{ relation: 'employee', scope: { where: { department_id: x } } }] });
Option 2: Nested Where Condition (Shorter Syntax)
If your ORM supports it, you can filter directly using the nested association field without explicitly scoping the include:
LeaveDetails.find({ where: { 'employee.department_id': x }, include: 'employee' // Include if you need employee data in the result; some ORMs require this for nested filtering }, (err, leaveRecords) => { // Handle result/error });
3. How It Works
- The
leave_detailsmodel is already linked toemployeevia theuser_idforeign key (per your existingleave_details.jsonconfig). - By adding the
departmentrelation toemployee, we can traverse the chain:leave_details→employee→department. - The query filters out any
leave_detailsrecords where the associated employee'sdepartment_iddoesn't matchx.
内容的提问来源于stack exchange,提问作者jayanes

