Closed ChayoPerez closed 3 years ago
Puedes mandar el código que utilizas para hacer la asociación?
¿¿Qué asociaciones tengo que utilizar?? Tenía entendido que esas cosas se usaban cuando se hacían relaciones entre modelos distintos, pero quizás me estoy equivocando de concepto. ¿Cómo sería el código? Gracias
Ah, es que mencionaste una asociación en la pregunta original.
Si es que te referías al modelo, por favor mándame el contenido de este.
Este es el modelo!
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class organization extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
}
};
organization.init({
name: DataTypes.STRING,
url: DataTypes.STRING
}, {
sequelize,
modelName: 'organization',
});
return organization;
};
Por si acaso aquí está el controlador también:
const KoaRouter = require('koa-router');
//const { where } = require("sequelize");
const router = new KoaRouter();
const PERMITTED_FIELDS = [
"name",
"url",
];
router.param("id", async (id, ctx, next) => {
// usamos ctx.state para enviar algo a otro middleware
// ctx.orm.user significa el modelo user dentro de sequelize
const organization = await ctx.orm.organization.findByPk(id);
if (!organization) ctx.throw(404); // si no existe retorna not found
ctx.state.organization = organization;
return next();
});
router.get("organizations", "/", async (ctx) => {
//const { cloudinary } = ctx.state;
//const organization = ctx.state.currentOrganization;
const organizations = await ctx.orm.organization.findAll({ include: "organization" });
/* organizations.forEach(org => {
org.dataValues.cloudinaryImage = cloudinary.url(org.image);
}); */
await ctx.render("organizations/index", {
organizations,
});
});
router.get("organizations-new", "/organizations/new", async (ctx) => {
const organization = ctx.orm.organization.build();
return ctx.render("organizations/new", {
organization,
});
});
router.post("organizations-create", "/", async (ctx) => {
const organization = ctx.orm.organization.build(ctx.request.body);
/* const { cloudinary } = ctx.state;
const { image } = ctx.request.files;
let recipeImageId;
if (image.size > 0) {
const uploadedImage = await cloudinary.uploader.upload(image.path);
recipeImageId = uploadedImage.public_id;
}
recipe.image = recipeImageId; */
try {
await organization.save({ fields: PERMITTED_FIELDS });
ctx.redirect(ctx.router.url("organization", { id: organization.id }));
} catch (error) {
await ctx.render("organizations/new", {
errors: error.errors,
});
}
});
router.get("organization-show", "organization/:id", async (ctx) => {
// await ctx.orm.like.destroy({where: {}}).then(function () {});
const organization = await ctx.orm.organization.findByPk(id);
return ctx.render("organizations/show", {
organization,
});
});
module.exports = router;
Y el routes
const KoaRouter = require('koa-router');
const router = new KoaRouter();
const hello = require('./routes/hello');
const hello2 = require('./routes/hello2');
const index = require('./routes/index');
const organizations = require('./routes/organizations');
router.use('/', index.routes());
router.use('/hello', hello.routes());
router.use('/organizations', organizations.routes());
module.exports = router;
Crees que puedas subir tu código a algún repo y compartírmelo?
Hola 😁
Lo que te está levantando el error es esta línea:
const organizations = await ctx.orm.organization.findAll({ include: "organization" });
Si te fijas, a findAll
le estás pasando como argumento el objeto { include: 'organization' }
.
Con esto de abajo debería bastar para obtener un listado de todas las organizaciones:
const organizations = await ctx.orm.organization.findAll()
Muchas muchas gracias por la ayuda! Ahora funciona, qué felicidad x))))
Hola! Estoy teniendo un problema en el programa que hice para practicar. El error, que ocurre al abrir una vista de organizations, dice
Tengo entendido que es porque se confunde con los nombres que le puse a las cosas (plural vs. singular) El nombre de mi modelo es organization.js El nombre de mi route is organizations.js Mis vistas están en la carpeta organizations Mi tabla correspondiente en la base de datos es organizations. Tengo que cambiar alguno de nombre para que se haga bien la asociación?
Graciaas, saludos