BUG: Foreign key & query scopes

#1

In a hasMany() relationship,:

hasMany(relatedModel, primaryKey, foreignKey)

foreignKey

Defaults to tableName_primaryKey of the current model. The singular form of the table name is used (for example, the foreign key user_id references the id column on the table users ).,

Let us say a User hasMany Post:

class User extends Model {

  static get primaryKey() {
    return 'name'
  }
  static scopeHasPosts (query) {
    return query.has('posts')
  }

  posts () {
    return this.hasMany('App/Models/Post')
  }

}

In this situation, posts.foreignKey still defaults to user_id even if in the migration file I also specified how the foreign key should be: user_name and even if I added in Post this method:

class Post extends Model {

  static get foreignKey() {
    return 'user_name'
  }

}

Now when I run this:

const users = await User.query().hasPosts().fetch()

The server complains about the fact it can not find posts.user_id in the database even if I instructed it what to use as a foreign key both on the model and migration levels.

This sounds to be a bug . @virk @romain.lanz

0 Likes

#2

Hi.

  1. the migration file is only for table creation / migration which it will not use in the Lucid model, so it will not affect how the model works.
  2. the foreignKey function only have getter which you cannot set by yourself, https://github.com/adonisjs/adonis-lucid/blob/develop/src/Lucid/Model/index.js#L113

In your case, the foreign key for your relation will always be user_id, so if you are going to use a foreign key other than _id, you should define it in the parameter of hasMany function.

I read your code, looks like your are try to add relation to user.name with post.user_name, please try:

posts () {
    return this.hasMany('App/Models/Post', 'name', 'user_name')
  }
2 Likes

#3

I still did not test this, but I believe all this is true because now I remember I read all this previously. So I accept your answer, thank you very much for the help.

0 Likes