Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/Lucid/Model/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
71 changes: 71 additions & 0 deletions test/unit/lucid.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
}
Expand Down