Attaching relations
See original GitHub issueI’m pretty sure that I’ve got something terribly wrong. I’ve got the following models:
var Project = bookshelfInstance.Model.extend({
tableName: 'projects',
tasks: function () {
return this.hasMany(Task)
}
})
var Task = bookshelfInstance.Model.extend({
tableName: 'tasks',
project: function () {
return this.belongsTo(Project)
}
})
I could not figure how to save a task with the relation to projects set, here’s whart I’m doing:
var task = new Task({description: 'Just do it!'})
Project.forge({id: 1}).fetch()
.then(
function (project) {
console.log(project)
return when(task.related('project').set(project)).yield(task)
})
.then(function (task) {
console.log(task)
return task.save()
})
.otherwise(function (error) {
console.log(error)
})
Postgres then answers with a constraint violation since project id on tasks
id defined as NOT NULL
:
/usr/local/bin/node --debug-brk=62219 bookshelf-playground.js
debugger listening on port 62219
{ sql: 'select "projects".* from "projects" where "id" = ? limit 1',
bindings: [ 1 ],
__cid: '__cid3' }
[ 'Project',
{ attributes: { id: 1, description: 'PROJECT A' },
_previousAttributes: { id: 1, description: 'PROJECT A' },
changed: {},
relations: {},
cid: 'c2',
id: 1,
_handleResponse: [Function],
_handleEager: [Function] } ]
[ 'Task: ',
{ attributes: { description: 'Just do it!' },
_previousAttributes: {},
changed: { description: 'Just do it!' },
relations: { project: [Object] },
cid: 'c1',
_handleResponse: [Function],
_handleEager: [Function] } ]
{ sql: 'insert into "tasks" ("description") values (?) returning "id"',
bindings: [ 'Just do it!' ],
__cid: '__cid4' }
{ [error: null value in column "project_id" violates not-null constraint]
length: 118,
name: 'error',
severity: 'ERROR',
code: '23502',
detail: undefined,
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
file: 'execMain.c',
line: '1572',
routine: 'ExecConstraints' }
Test case:
schema.sql
DROP TABLE tasks;
DROP TABLE projects;
CREATE TABLE projects (
id SERIAL NOT NULL,
description CHARACTER VARYING(64),
CONSTRAINT projects_pkey PRIMARY KEY (id)
);
CREATE TABLE tasks (
id SERIAL NOT NULL,
project_id INTEGER NOT NULL,
description CHARACTER VARYING(256),
CONSTRAINT tasks_pkey PRIMARY KEY (id)
);
ALTER TABLE tasks ADD CONSTRAINT tasks_projects_fk FOREIGN KEY (project_id) REFERENCES projects (id);
INSERT INTO projects (description) VALUES ('PROJECT A');
INSERT INTO projects (description) VALUES ('PROJECT B');
app.js
var Bookshelf = require('bookshelf'),
when = require('when')
bookshelfInstance = Bookshelf.initialize({
client: 'postgres',
connection: {
host: 'localhost',
user: '***',
database: 'playground',
charset: 'utf8'
},
debug: true
})
var Project = bookshelfInstance.Model.extend({
tableName: 'projects',
tasks: function () {
return this.hasMany(Task)
}
})
var Task = bookshelfInstance.Model.extend({
tableName: 'tasks',
project: function () {
return this.belongsTo(Project)
}
})
var task = new Task({description: 'Just do it!'})
Project.forge({id: 1}).fetch()
.then(
function (project) {
console.log(['Project', project])
return when(task.related('project').set(project)).yield(task)
})
.then(function (task) {
console.log(['Task: ', task])
return task.save()
})
.otherwise(function (error) {
console.log(error)
})
Issue Analytics
- State:
- Created 10 years ago
- Comments:35 (13 by maintainers)
Top Results From Across the Web
How Attachment Styles Affect Adult Relationships
Attachment styles or types are characterized by the behavior exhibited within a relationship, especially when that relationship is threatened.
Read more >Eloquent: Relationships - The PHP Framework For Web Artisans
Eloquent relationships are defined as methods on your Eloquent model classes. ... an empty App\Models\User model if no user is attached to the...
Read more >I'm Emotionally Attached To Someone? - ReGain
An emotional attachment could be unhealthy when a person depends on their relationship while feeling insecure, anxious, or fearful of losing their partner....
Read more >Emotional Attachment: 4 Things to Know - Healthline
Emotional attachment refers to the feelings of closeness and affection that help sustain meaningful relationships over time.
Read more >Attachment Styles and Their Role in Adult Relationships
The four attachment styles are 1. Anxious (Preoccupied) 2. Avoidant (Dismissive) 3. Disorganized (Fearful-Avoidant) and 4. Secure.
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Reopening this since creating related models still sucks.
Can we get some documentation on the homepage about attaching related models? I’d be happy to contribute it, but I’ve been using bookshelf for about six months now and it’s still not clear to me what the ‘normal’ way to attach models for each relation type is.