[英]Get All Relationship Data in AdonisJS
does anyone know how to retrieve all the data including from the relationship in AdonisJS?有谁知道如何从 AdonisJS 中的关系中检索所有数据? , so I want to retrieve the user data from the User Model including the relationship data in the Post Model.
,所以我想从用户 Model 中检索用户数据,包括 Post Model 中的关系数据。
get All users获取所有用户
public async getUsers({ response }: HttpContextContract) {
try {
const data = await User.all()
return response.status(200).send({ "result": data })
} catch(err) {
return response.status(400).json({ error: err.message })
}
}
First: You can use belongsTo in User model to make relationship data with Post model第一:您可以在用户model中使用belongsTo与Post model建立关系数据
post_model() {
return this.belongsTo("App/Models/Post")
}
Second: Call the model use query like this:第二:调用 model 使用查询,如下所示:
await User.query()
.with("post_model", builder => {
builder.select("id", "name", "post")
})
First, you will need to define the relationships on your model.首先,您需要在 model 上定义关系。
A User
has many Posts
:一个
User
有很多Posts
:
export default class User extends BaseModel {
...
@hasMany(() => Post) // 👈 One-to-many relationship
public posts: HasMany<typeof Post>
}
A Post
belongs to a User
:一个
Post
属于一个User
:
export default class Posts extends BaseModel {
...
@belongsTo(() => User) // 👈 a Post belongs to a User
public user: BelongsTo<typeof User>
}
Now, in your query, you can preload the relationship .现在,在您的查询中,您可以预加载关系。
const users = await User
.query()
.preload('posts')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.