Question

I've got a structure like this, for a 'session':

{
  "created_at": Tue Apr 22 2014 23:10:52 GMT+00:00 ,
  "id":  "960e9a45-9a06-43c5-be7f-9144ee3f67c8" ,
  "scheduled_time": Wed Apr 23 2014 02:00:00 GMT+00:00 ,
  "reservation": {
    "created_at": Mon Apr 21 2014 03:00:26 GMT+00:00 ,
    "student_id":  "8be76323-98ce-488e-9164-611663bc17ec"
  }
}

I can easily perform a join on reservation.student_id with:

r.table('sessions').eqJoin(
  r.row('reservation')('student_id'), 
  r.table('users')
)

My problem is that a session won't necessarily be reserved, that attribute is only added once a student actually reserves the session. So if any sessions exist in the table that don't get have a reservation, Rethink tells me No attribute 'reservation' in object.

Someone in IRC recommended the following:

r.table('sessions').withFields("reservation").eqJoin(
    r.row("reservation")("student_id"), 
    r.table("users")
)

However, this query will ONLY retrieve sessions that currently have a reservation. I'd like to get all sessions, while also performing a join for those sessions which do have a reservation. Is there a way to do this with a single query, or would I just need to perform a second query after the first to grab the sessions without reservations? Do I need to model my data differently?

Was it helpful?

Solution

The output is slightly different than with eqJoin, but does that work for you?

r.table('sessions').map(function(session) {
    return r.branch(
        session.hasFields("reservation"),
        {
            session: session,
            reservations: r.table("users").getAll(session("reservation")("student_id")).coerceTo("ARRAY")
        },
        {
            session: session
        }
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top