Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updating a model with a composite primary key #720

Closed
nathasm opened this issue May 2, 2015 · 5 comments
Closed

Updating a model with a composite primary key #720

nathasm opened this issue May 2, 2015 · 5 comments

Comments

@nathasm
Copy link

nathasm commented May 2, 2015

I have a model that is set up to have a composite primary key:

knex.schema.createTable('table', function(t) {
  ....
  t.primary(['user_id', 'another_id'])
});

When using bookshelf, I have a User model with a function 'add' that will add the user or update the user if they already exist. I'm doing something like:

  add: function(data, attrs) {
    return User.forge(data).fetch().then(function(user) {
      if(user) {
        // If I remove the update, it assumes insert and save fails since the primary key already exists
        return user.save({ attrs: attrs }, { method: 'update' });
      }
      return User.forge(connection).save();
    });
  },

The code above, as written, yields an error of

Error: A model cannot be updated without a "where" clause or an idAttribute.

Is there a way to save/update the user with a composite key by just doing 'save' or do I need to include the 'where' clause as well?

@gdw2
Copy link

gdw2 commented May 14, 2015

I'm having the same problem.

@rhys-vdw
Copy link
Contributor

Unfortunately bookshelf does currently not support composite keys.

Is there a way to save/update the user with a composite key by just doing 'save' or do I need to include the 'where' clause as well?

You'll have to use a where clause for now.

I'm going to close this as a duplicate as this issue is being tracked in #93.

@kc5ez
Copy link

kc5ez commented Sep 7, 2016

@rhys-vdw

I am also trying to save/update a table that has composite keys. since bookshelf doesn't support composite keys, should we just get rid of composite key completely and use another ORM?

What is a workaround?

Can you provide an example of using the where clause in the save function? I've tried it but still trying to return 'id' (which does not exist)

@dnascimento
Copy link

@kichingxx just use where clause like:

new model().where({key: keyVal}).save(obj)

However, compose keys should be a bookshelf feature...

@ItsShadowCone
Copy link

Unfortunately bookshelf does currently not support composite keys.

Has this changed in the past ~2 years?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

6 participants