我试图在此处设置一个钩子,但是,检查标签是否存在似乎有问题。
这里是PostController
'use strict'
const { validateAll } = use('Validator')
const Post = use('App/Models/Post')
class PostController {
create ({ view }) {
return view.render('posts.create')
}
async store ({ request, session, response, auth }) {
const { title, tag, body } = request.all()
const rules = {
title: 'required',
tag: 'required|exists:tags,id',
body: 'required'
}
const validation = await validateAll(request.all(), rules)
if (validation.fails()) {
session.withErrors(validation.messages())
.flashAll()
return response.redirect('back')
}
const post = new Post()
post.fill({
title,
body,
tag_id: tag,
user_id: auth.user.id
})
await post.save()
return response.route('home') // @todo update
}
}
module.exports = PostController
这是hooks.js
const { hooks } = require('@adonisjs/ignitor')
const pluralize = require('pluralize')
hooks.after.providersBooted(() => {
const View = use('View')
const Tag = use('App/Models/Tag')
Tag.all().then((tags) => {
View.global('tags', tags)
}).catch(() => {
//
})
const Validator = use('Validator')
const Database = use('Database')
const exists = async (data, field, message, args, get) => {
const value = get(data, field)
if (!value) {
return
}
const [table, column] = args
const found = await Database.table(table).where(column, value).first()
if (!found) {
throw message
}
}
Validator.extend('exists', exists)
})
我有一个标签列表,但出现以下错误
select * from "tags" where "id" = $1 limit $2 - invalid input syntax for integer: "Tag"
如果我将tag: 'required|exists:tags,id',
更改为tag: 'required',
,则可以使用,但是我想检查标签是否存在。