dresende / node-orm2

Object Relational Mapping
http://github.com/dresende/node-orm2
MIT License
3.07k stars 379 forks source link

Model.hasOne join on specific fields with conditions ? #578

Open kdbo opened 9 years ago

kdbo commented 9 years ago

I have a model , timesheet, having a user_id, date and some other fields. another model, holiday has user_id and date_from, date_until date fields.

Like this:

db.define('timesheet',{
   id: {type: "serial",key:true},
   regdate: {type:'date', time:false},
   employee_id: {type: Integer}
});
db.define('holiday',{
   id: {type: "serial", key:true},
   date_from: {type:'date',time:false},
   date_until: {type:'date',time:false},
   some_otherfield: {type: 'text'},
   employee_id: {type: Integer}
});

var TimeSheet = db.models.timesheet;
TimeSheet.hasOne('employee',db.models.employee,{autofetch: true});
var Holiday = db.models.holiday;
Holiday.hasOne('employee',db.models.employee,{autofetch: true});

I am trying to add the Holiday object to the TimeSheet on employee_id where TimeSheet.regdate is between Holiday.date_from and Holiday.date_until.

I cant figure it out :-/

toddpi314 commented 9 years ago

Perhaps I don't understand the problem here.

If you are 'trying to add the Holiday object to the Timesheet', you will need to couple the holiday model to the timesheet model using either a hasOne or hasMany relationship.

Based on the problem, I am guessing you are asking, "How can I find out which holidays are associated to a given timesheet with the above schema?"

In that case, you can discover this at runtime using the get/set accessors and the first parameter filter criteria. Something like 'timesheetInstance.getHoliday({ employee_id: 234 }, ..)', assuming you make the holiday relationship mentioned above.

Also, go check out the minimally documented 'findBy' accessor autogenerated on the static model to get at these things without drafting the relationship.

Hope that helps!