Revisit API for singleRelation/manyRelation/join
- Dominant language
- TypeScript
- Stars
- 12.9k
- Forks
- 625
- Avg merge
- 5h 23m
- Merged PRs (30d)
- 24
Description
User requested how to make this code return a flattened list:
```ts
stops($route) {
const feedID = $route.get('feed_id');
const routeID = $route.get('route_id');
return each(trips.find({ feed_id: feedID, route_id: routeID }), t => {
return each(stop_times.find({ feed_id: feedID, trip_id: t.get('trip_id') }), st => {
return stops.find({ feed_id: feedID, stop_id: st.get('stop_id') }).single();
});
});
},
```
Solution was:
```ts
stops($route) {
const $feedID = $route.get('feed_id');
const $routeID = $route.get('route_id');
const $stops = stops.find();
const sqlFeedId = $stops.placeholder($feedID);
const sqlRouteId = $stops.placeholder($routeID);
$stops.where(sql`
${stops}.feed_id = ${sqlFeedId}
and stop_id in (
select stop_id
from stop_times
where stop_times.feed_id = ${sqlFeedId}
and stop_times.trip_id in (
select trips.trip_id
from trips
where trips.feed_id = ${sqlFeedId}
and trips.route_id = ${sqlRouteId}
)
)
`);
return $stops;
},
```
Solution is ugly. Would be good to have a nicer API for this.
I tried starting at stops and using `singleRelation`, but that only lets me go one layer - instead of returning SQL we should return an object that allows you to traverse additional layers.
`manyRelation` doesn't exist.
I also tried with join, but having to define each of the aliases was a real chore, we should make this easier/nicer.
The API the user used was straightforward to understand (they were looking for a `flatten()` method), we should aim for a similarly clean approach that still yields `$stops` to allow for orderBy/conditions/connection/etc.
Contributor guide
Assessment
This issue has not been assessed yet.