[英]How to fetch single row using withGraphJoined?
There are two tables users and activities.有两个表用户和活动。
I am able to join these using withGraphJoined
.我可以使用withGraphJoined
加入这些。 The response json is like this,响应 json 是这样的,
[
{
user: 'first',
activity: [{ type: 'act1' }, { type: 'act2' }],
},
{
user: 'second',
activity: [{ type: 'act3' }, { type: 'act2' }],
},
];
Now i want to fetch only the first activity and make current array into first activity object.现在我只想获取第一个活动并将当前数组变成第一个活动 object。 {user:"second", activity:{type:"act3}}
I tried this but still i get all the activity in array.我试过了,但我仍然得到了数组中的所有活动。
User.query()
.withGraphJoined('activity')
.modifyGraph('activity', (builder) => builder.first());
This depends on how you define the relationship if you want it to return a single object then the relation should use Model.HasOneRelation
or Model.BelongsToOneRelation
这取决于您如何定义关系,如果您希望它返回单个 object,那么该关系应使用Model.HasOneRelation
或Model.BelongsToOneRelation
however if you just want to return a single activity from many you can limit the results但是,如果您只想从多个活动中返回单个活动,则可以限制结果
.modifyGraph('activity', (builder) => builder.orderBy('created_at', 'desc').limit(1));
but it will still return an array with one item that you can access by activity[0]
the only way i can think of is if you manually map this first item in your then
like但它仍然会返回一个数组,其中包含一个您可以通过activity[0]
我能想到的唯一方法是如果您手动 map 这第一项在您的then
喜欢
.then(user => {
user.activity = user.activity[0] ? user.activity[0] : {}
res.json(user)
})
to be on the safe side, you can check if the item exists first to avoid null error为了安全起见,您可以先检查该项目是否存在以避免 null 错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.