diff --git a/src/Lucid/Model/index.js b/src/Lucid/Model/index.js index 629d4eab4..469f01458 100644 --- a/src/Lucid/Model/index.js +++ b/src/Lucid/Model/index.js @@ -780,6 +780,21 @@ class Model extends BaseModel { return evaluatedAttrs } + /** + * Checks if the passed model instance's record is the same as the current + * + * @method is + * @param {Model} model + * + * @return {Boolean} + */ + is (model) { + return !!model && + this.primaryKeyValue === model.primaryKeyValue && + this.constructor.table === model.constructor.table && + this.constructor.connection === model.constructor.connection + } + /** * Persist model instance to the database. It will create * a new row when model has not been persisted already, diff --git a/test/unit/lucid.spec.js b/test/unit/lucid.spec.js index 7966f0362..2764ad1ac 100644 --- a/test/unit/lucid.spec.js +++ b/test/unit/lucid.spec.js @@ -113,6 +113,77 @@ test.group('Model', (group) => { assert.deepEqual(user.$attributes, { username: 'virk', age: 22 }) }) + test('can verify that two models hold the same record', (assert) => { + class User extends Model {} + + const user = new User() + user.id = 1 + const user2 = new User() + user2.id = 1 + + assert.isTrue(user.is(user2)) + }) + + test('can verify that two models do not hold the same record based on primary key', (assert) => { + class User extends Model {} + + const user = new User() + user.id = 1 + const user2 = new User() + user2.id = 2 + + assert.isFalse(user.is(user2)) + }) + + test('can verify that two models do not hold the same record when comparing against an empty model', (assert) => { + class User extends Model {} + + const user = new User() + + assert.isFalse(user.is(null)) + }) + + test('can verify that two models do not hold the same record based on table', (assert) => { + class User extends Model {} + class Post extends Model {} + + const user = new User() + user.id = 1 + const post = new Post() + post.id = 1 + + assert.isFalse(user.is(post)) + }) + + test('can verify that two models do not hold the same record based on connection', (assert) => { + class SqliteUser extends Model { + static get connection () { + return 'sqlite' + } + + static get table () { + return 'user' + } + } + + class MysqlUser extends Model { + static get connection () { + return 'mysql' + } + + static get table () { + return 'user' + } + } + + const user = new SqliteUser() + user.id = 1 + const user2 = new MysqlUser() + user2.id = 1 + + assert.isFalse(user.is(user2)) + }) + test('remove existing attributes when calling fill', (assert) => { class User extends Model { }