为什么要在model和migration上设置数据库的关系?阿多尼斯 JS
Why we have to set the relations of the database at model and migration? Adonis JS
为什么 Adonis.js 需要设置迁移数据库中存在的关系(带参考)和模型中的关系(带 hasMany)?
总而言之,迁移和模型是独立的,不能协同工作。要使用模型,无需使用迁移(您可以使用现有数据库)。
迁移
迁移用于创建数据库。
您必须在迁移文件中定义数据库的结构。所以关系很重要。
Migrations are documented database mutations, created throughout your application’s development lifecycle that you can roll back or re-run at any point in time.
Migrations make it easier to work as a team, enabling database schema changes from one developer to be easily tracked and then applied by other developers in your organization.
当然,迁移不是必须的。您可以创建自己的数据库并仅使用允许您检索数据的 models 。
Models - Relationships
关于模型 (Lucid) 的有趣之处在于它很容易进行 SQL 查询(使用 Knex)。
由于模型和迁移没有关联,因此有必要声明您将要使用的表之间的不同关系。
Lucid 是 active record pattern.
的 AdonisJS 实现
Relationships are the backbone of data-driven applications, linking one model type to another.
For example, a User could have many Post relations, and each Post could have many Comment relations.
Lucid’s expressive API makes the process of associating and fetching model relations simple and intuitive, without the need to touch a SQL statement or even edit a SQL schema.
示例:
关系:
用户模型:
const Model = use('Model')
class User extends Model {
posts () {
return this.hasMany('App/Models/Post') // has many Post
}
}
module.exports = User
控制器代码:
const User = use('App/Models/User')
const users = await User
.query()
.with('posts') // Use model relationship
.fetch()
输出:
[
{
id: 1,
username: 'virk',
posts: [{
id: 1,
user_id: 1,
post_title: '...',
post_body: '...',
}]
}
]
为什么 Adonis.js 需要设置迁移数据库中存在的关系(带参考)和模型中的关系(带 hasMany)?
总而言之,迁移和模型是独立的,不能协同工作。要使用模型,无需使用迁移(您可以使用现有数据库)。
迁移
迁移用于创建数据库。
您必须在迁移文件中定义数据库的结构。所以关系很重要。
Migrations are documented database mutations, created throughout your application’s development lifecycle that you can roll back or re-run at any point in time.
Migrations make it easier to work as a team, enabling database schema changes from one developer to be easily tracked and then applied by other developers in your organization.
当然,迁移不是必须的。您可以创建自己的数据库并仅使用允许您检索数据的 models 。
Models - Relationships
关于模型 (Lucid) 的有趣之处在于它很容易进行 SQL 查询(使用 Knex)。
由于模型和迁移没有关联,因此有必要声明您将要使用的表之间的不同关系。
Lucid 是 active record pattern.
的 AdonisJS 实现Relationships are the backbone of data-driven applications, linking one model type to another.
For example, a User could have many Post relations, and each Post could have many Comment relations.
Lucid’s expressive API makes the process of associating and fetching model relations simple and intuitive, without the need to touch a SQL statement or even edit a SQL schema.
示例:
关系:
用户模型:
const Model = use('Model')
class User extends Model {
posts () {
return this.hasMany('App/Models/Post') // has many Post
}
}
module.exports = User
控制器代码:
const User = use('App/Models/User')
const users = await User
.query()
.with('posts') // Use model relationship
.fetch()
输出:
[
{
id: 1,
username: 'virk',
posts: [{
id: 1,
user_id: 1,
post_title: '...',
post_body: '...',
}]
}
]