I'm trying to save sequelize models with their associations. All the associations are one to one. Retrieving models with associations from the database works just fine but inserting them is another matter and the documentation is just making me more confused.
Here's my insert method:
models
.radcheck
.create(user, {
include: [{model: models.skraningar}, {model: models.radusergroup}, {model: models.radippool}]
})
.then(success, error);
I've seen so many ways to do this both in the documentation and here on stackoverflow and none of them make sense to me so far. Anyone care to clear things up for me?
I always save a model with association by it's foreign key
e.g
models.user.create({ name : 'test', usergroup_id : 1 });
Related
I've just installed Loopback4 (based on TS) and i'm trying to play around with it since it seems really easy to create an API using it. My question is rather simple (yet i dont know the answer). How can i increment the id of my model ?
Lets say i've got this in my model (created with lb4 model) ->
export class Post extends Entity {
#property({
type: 'number',
id: true,
required: false,
})
Id: number;
The first post (without adding ID) creates it with Id = 0. There's no next post since the Id doesnt auto-increment.
Any tip on how to do it? I'm using MySQL as stated in my title and LB4.
EDIT: Or even better, is there any way to modify the way Loopback4 (loopback-next) creates tables ? Theres one command that would need to be run after the DB tables have been created, something like ALTER TABLE post CHANGE Id Id INT(11) NOT NULL AUTO_INCREMENT;
I keep searching through the tree of options, but i've found nothing relevant and i dont think connecting to the db separately for this task is a good idea.
Fixed thanks to github. Apparently it is very similar to LB3 (which i didnt use).
#property({
type: 'number',
id: true,
generated: true,
})
Id: number;
Adding generated: true turns on the auto-increment on mysql.
I would like to know if we can fetch a table model from MySql from Database, without defining all the properties.
I'm using Node.js ORM2
const orm = require('orm');
db.define('users', {
// donot want to specify all the properties/fields
});
Above users table has already been created in DB, so I just want to get that model and not create/specify all the properties in it.
We can do this with other ORM's like Objection.js - but can't change my current implementation.
Thanks in advance,
Unfortunately, you must define properties/fields while you are defining your Models. There aren't any other options.
I've tried to search before posting this question, but no success.
I'm having some troubles trying to understand the best way to achieve a many-to-many association in SailsJS.
Ex:
Hospital has many specialties
Specialty has many hospitals
How do I represent the tables in MySQL so the SailsJS operate on them?
I have an Hospital table and a Specialty table.
Do I have to have an Hospital_Specialty (not sure about if this is the correct tablename to use) table to handle those associations? Like:
Hospital_Specialty
id: int
hospital_id: int
specialty_id: int
I've read the documention but no luck on getting a proper way to achieve what I need.
Thanks in advance
Edit: My initial answer was totally wrong.
The documentation for setting up many <-> many relationships is here:
Many-to-Many | Sails.js
First of all, you'll want to work in Waterline rather than mysql to get this to work properly.
You can set up a many relationship in your model like so:
Specialty.js Model
module.exports = {
attributes: {
hospitals:{
collection: 'hospital',
via: 'specialties'
}
}
}
Hospital.js Model
module.exports = {
attributes: {
specialties:{
collection: 'specialty',
via: 'hospitals'
}
}
}
This will set up the required intermediate tables.
Up to you if you want to use plurals or not.
I am using Sequelize, but since I also have other servers running other than node.js, I need to let them share the database. So when defining one-to-many relation, I need to let Sequelize use the old existing jointTable.
I write my definition of the association as below, where pid is the primary key of presentations:
this.courses.hasMany(this.presentations,
{as : 'Presentations',
foreignKey : 'cid',
joinTableName : 'course_presentations'
});
Or this one:
this.courses.hasMany(this.presentations,
{as : 'Presentations',
foreignKey : 'pid',
joinTableName : 'course_presentations'
});
I am using the below codes to retrieve the associated presentations:
app.get('/courses/presentations/:cid', function (req, res){
var cid = req.params.cid;
app.models.courses.find({where: {cid:cid}}).success(function(course){
course.getPresentations().success(function(presentations){
res.send(presentations);
});
});
});
The previous one will tell me there is no cid in 'presentations' table.
The latter one will give something like this:
Executing: SELECT * FROM `courses`;
Executing: SELECT * FROM `courses` WHERE `courses`.`cid`='11' LIMIT 1;
Executing: SELECT * FROM `presentations` WHERE `presentations`.`pid`=11;
Check carefully, I found that everytime, it is always using the cid value to query for presentations, which means only when they happen to share the same id value, something can be returned. And even for those, it is not correct.
I am strongly suspecting, Sequelize are not using the joinTable I specified, instead, it is still trying to find the foreign keys in the original two tables. It is viewing pid as the reference of cid in presentations, which causes this problem.
So I am wondering how to correctly set up the junction table so that the two of them can use the foreign keys correctly.
jointTableName : 'course_presentations'
should be (without a t)
joinTableName : 'course_presentations'
Actually AFAIK - this kind of relation is not "pure" one-to-many.
You have one course can have many entries in course_presenation table, and course_presentation have one-to-one relation with presentation. If so, just define that kind of associations in model.
I am working to use django's ContentType framework to create some generic relations for a my models; after looking at how the django developers do it at django.contrib.comments.models I thought I would imitate their approach/conventions:
from django.contrib.comments.models, line 21):
content_type = models.ForeignKey(ContentType,
verbose_name='content type',
related_name="content_type_set_for_%(class)s")
object_pk = models.TextField('object ID')
content_object = generic.GenericForeignKey(ct_field="content_type", fk_field="object_pk")
That's taken from their source and, of course, their source works for me (I have comments with object_pk's stored just fine (integers, actually); however, I get an error during syncdb on table creation that ends:
_mysql_exceptions.OperationalError: (1170, "BLOB/TEXT column 'object_pk' used in key specification without a key length")
Any ideas why they can do it and I can't ?
After looking around, I noticed that the docs actually state:
Give your model a field that can store a primary-key value from the models you'll be relating to. (For most models, this means an IntegerField or PositiveIntegerField.)
This field must be of the same type as the primary key of the models that will be involved in the generic relation. For example, if you use IntegerField, you won't be able to form a generic relation with a model that uses a CharField as a primary key.
But why can they do it and not me ?!
Thanks.
PS: I even tried creating an AbstractBaseModel with these three fields, making it abstract=True and using that (in case that had something to do with it) ... same error.
After I typed out that really long question I looked at the mysql and realized that the error was stemming from:
class Meta:
unique_together = (("content_type", "object_pk"),)
Apparently, I can't have it both ways. Which leaves me torn. I'll have to open a new question about whether it is better to leave my object_pk options open (suppose I use a textfield as a primary key?) or better to enforce the unique_togetherness...