简体   繁体   English

如何使用 withGraphJoined 获取单行?

[英]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.HasOneRelationModel.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.

相关问题 如何使用php和mysql在单行引导滑块中获取不同的数据结果 - how can i fetch different data results in single row of bootstrap slider using php and mysql 如何使用DataTables获取行值并删除数据? - How to fetch row values and delete data using DataTables? 如何使用 fetch API 在 javascript 中下载具有多个块的单个文件 - How to download single file with multiple chunks in javascript using fetch API 如何使用JavaScript将多个下拉列表选择的值提取到单个数组中 - How to fetch multiple dropdowns selected value into a single array using JavaScript 如何使用messages.fetch删除一条消息? - How to delete a single message using messages.fetch? 如何通过使用javascript单击按钮来获取特定行列的值 - how to fetch value of particular row column by clicking button using javascript 如何使用Java脚本获取单个变量中的所有值 - how to fetch all values in single variable using java script 如何使用jQuery通过键搜索和获取JSON行数据? - How to search and fetch json row data by key using jQuery? 如何使用jQuery仅在一行中合并2个td? - How to merge 2 td in a single td only in a row using jQuery? 无法使用 Javascript 获取行元素值 - Unable to fetch row elements values using Javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM