how to set alias for fields on AdonisJS ORM? - adonis.js

I'm trying to get state, city and slaughter from this query. I've tried this and it only returns 1 of them as 'name' which is name of each place in 'places' table. how can I get alias for them? I didn't find anything on documents.
const bargiris = await Database
.table('bargiris')
.innerJoin('users', 'bargiris.nazer_id', 'users.id')
.innerJoin('companies', 'bargiris.sherkat_id', 'companies.id')
.innerJoin('sifs', 'bargiris.sif_code', 'sifs.sif_id')
.innerJoin('places', function() {
this.on('sifs.state_id', 'places.id')
.orOn('sifs.city_id', 'places.id')
.orOn('sifs.slaughter_id', 'places.id')
})

You can add the select() method and pass the field names with an alias
const bargiris = await Database
.table('bargiris')
.innerJoin('users', 'bargiris.nazer_id', 'users.id')
.innerJoin('companies', 'bargiris.sherkat_id', 'companies.id')
.innerJoin('sifs', 'bargiris.sif_code', 'sifs.sif_id')
.innerJoin('places', function() {
this.on('sifs.state_id', 'places.id')
.orOn('sifs.city_id', 'places.id')
.orOn('sifs.slaughter_id', 'places.id')
})
.select('state.name as state', 'city.name as city')

Related

AdonisJS no default values for timestamps

I have created basic schema with timestamps, but when I insert into table in seeder, column created_at and updated_at are null, but based on the Knex.js documentation I thought it should be current datetime if not specified.
Latest adonis libraries, database: mysql 5.7.
My Schema
'use strict'
const Schema = use('Schema')
class UserSchema extends Schema {
up () {
this.create('users', (table) => {
table.increments()
table.string('name')
table.timestamps()
})
}
down () {
this.drop('users')
}
}
module.exports = UserSchema
My Seeder
'use strict'
const Factory = use('Factory')
const Database = use('Database')
class UserSeeder {
async run () {
await Database.table('users').insert({
name: 'JP',
})
}
}
module.exports = UserSeeder
Timestamps only works on LUCID ORM. You are using direct database.
Set your json in the fields, it will work:
await Database.table('users').insert({
name: 'JP',
created_at,: Database.fn.now(),
updated_at : Database.fn.now()
})
I have found that timestamps are default only when using models, but not when using database directly. This one is now covered in the documentation. Would be great if it was default on database level instead.
You should add the timestamps arguments like useTimestampType and makeDefaultNow:
table.timestamps(true, true)

Ember-data peekRecord returns null [duplicate]

A lot of the other posts on this topic are 2+ years old, so here goes a potentially simple question.
I am using Ember data relationships to have a 'bizinfo' record belong to a 'user' record. Seems simple, but I am having the worst time of it.
In app/models/bizinfo.js I have the line:
'ownedBy': DS.belongsTo('user')
And in my route, where I validate and then save the model, I have the following code:
user_id: Ember.computed(function(){
return `${this.get('session.data.authenticated.user_id')}`;
}),
user: Ember.computed(function(){
return this.store.findRecord('user', this.get('user_id'));
}),
model(params){
return this.store.createRecord('bizinfo', {'ownedBy': this.get('user')});
},
at this point if I go into the Ember inspector to look at the 'bizinfo' data object, I see the following under the belongsTo tab:
ownedBy : <(subclass of Ember.ObjectProxy):ember1053>
Here is the code from my submit action:
submit() {
let model = this.currentModel;
console.log(model.ownedBy);
console.log(`what does the model look like?`);
console.log(model.toJSON());
model.validate().then(({model, validations}) => {
if (validations.get('isValid')) {
this.setProperties({
showAlert: false,
isRegistered: true,
showCode: false
});
let success = (response) => {
console.log(`Server responded with ${response.toJSON()}`);
};
let failure = (response) => {
console.log(`Server responded with ${response}`);
};
model.save().then(success, failure);
} else {
this.set('showAlert', true);
}
this.set('didValidate', true);
}, (errors) => {
console.log(`errors from failed validation: ${errors}`);
});
},
So here is the result of the first console.log statement:
ComputedProperty {isDescriptor: true, _dependentKeys: undefined, _suspended: undefined, _meta: Object, _volatile: false…}
And when I look at the model.toJSON() log, I see
ownedBy: null
Can anyone see what's going wrong here? Is it the create record statement? I have tried a lot of different permutations (such as submitting just the id as the 'user' parameter.
findRecord will return a promise. A simple way to get around the issue is
model(params){
return this.store.findRecord('user', this.get('user_id')) .
then(ownedBy => this.store.createRecord('bizinfo', {ownedBy});
}
This will wait for the findRecord to resolve, then return a new record with the resolved value as the ownedBy property.

Ember data dependent keys undefined

A lot of the other posts on this topic are 2+ years old, so here goes a potentially simple question.
I am using Ember data relationships to have a 'bizinfo' record belong to a 'user' record. Seems simple, but I am having the worst time of it.
In app/models/bizinfo.js I have the line:
'ownedBy': DS.belongsTo('user')
And in my route, where I validate and then save the model, I have the following code:
user_id: Ember.computed(function(){
return `${this.get('session.data.authenticated.user_id')}`;
}),
user: Ember.computed(function(){
return this.store.findRecord('user', this.get('user_id'));
}),
model(params){
return this.store.createRecord('bizinfo', {'ownedBy': this.get('user')});
},
at this point if I go into the Ember inspector to look at the 'bizinfo' data object, I see the following under the belongsTo tab:
ownedBy : <(subclass of Ember.ObjectProxy):ember1053>
Here is the code from my submit action:
submit() {
let model = this.currentModel;
console.log(model.ownedBy);
console.log(`what does the model look like?`);
console.log(model.toJSON());
model.validate().then(({model, validations}) => {
if (validations.get('isValid')) {
this.setProperties({
showAlert: false,
isRegistered: true,
showCode: false
});
let success = (response) => {
console.log(`Server responded with ${response.toJSON()}`);
};
let failure = (response) => {
console.log(`Server responded with ${response}`);
};
model.save().then(success, failure);
} else {
this.set('showAlert', true);
}
this.set('didValidate', true);
}, (errors) => {
console.log(`errors from failed validation: ${errors}`);
});
},
So here is the result of the first console.log statement:
ComputedProperty {isDescriptor: true, _dependentKeys: undefined, _suspended: undefined, _meta: Object, _volatile: false…}
And when I look at the model.toJSON() log, I see
ownedBy: null
Can anyone see what's going wrong here? Is it the create record statement? I have tried a lot of different permutations (such as submitting just the id as the 'user' parameter.
findRecord will return a promise. A simple way to get around the issue is
model(params){
return this.store.findRecord('user', this.get('user_id')) .
then(ownedBy => this.store.createRecord('bizinfo', {ownedBy});
}
This will wait for the findRecord to resolve, then return a new record with the resolved value as the ownedBy property.

.pluck function in strongloop loopback?

Does storongloop loopback has pluck function for a given model ?
For a Product model,
in Rails I can write
Product.where(some_condition).pluck(:name)
It will return an array of names of products matching the condition.
Is there anything similar in loopback?
PS: I know I can use fields filter and then use underscore( or lodash)'s pluck but that's a two step process.
Select specific columns:
{"fields":{"name":true, "email":true}}
Where condition:
{"where":{"id":2}}
Combining:
{"fields":{"id":true},"where":{"id":{"inq":[10,20,30]}}}
The above code works in swagger. Node.js code would be as follows:
var m = server.models.customer;
m.findOne({
fields: ['name', 'email'],
where: {
id:{inq:[10,20,30]}}
}
}, function (err, data) {
console.log(data);
})

emberjs find then filter

In emberjs, considering the following data
(only showing 1 record, normally there would be multiple records):
{ "service": [{
"service-_id":"service_5606ece79bdb05546479739866",
"service-_rev":"5-62dc477c13ef3ea92869bcdf1a67f1a6",
"service-company-name":"ABC co.",
"service-address":"1 2 3 Main Street",
"service-address-line-2":"",
"service-city":"asfd",
"service-state-current":"NY",
"service-zip":"12345",
"service-phone":"111",
"service-fax":"",
"service-email":"asdf#adsf.com",
"service-category-current":"web",
"service-type":"service",
"id":"service_5606ece79bdb05546479739866"
}]}
If I want to return all the records, I can simply do this:
App.ServicesRoute = Ember.Route.extend({
model: function(){
return this.store.find('service');
}
});
However, let's say I want to return all the records that have the current category as 'web'. So in the example data, there is this key: service-category-current
How would I adjust my model to find 'service' then filter where service-category-current = 'web' ?
The best way would be to make your API backend handle query params you send to it (so your records would be filtered on a backend, preferably query params could be used to query the database), so response from server would return only records that match your query. Example store.query call:
this.store.query('service', {
'service-category-current': 'web'
});
Which results in fetching records from URL:
http://api.com/services?service-category-current=web
And you're done. But, if you can't refactor your backend, you could filter records client-side:
model() {
return new Ember.RSVP.Promise(resolve => {
this.store.findAll('service').then(services => {
resolve(services.filterBy('service-category-current', 'web'));
});
});
}
Not ES2015 + using Ember.RSVP.Promise instead of native Promise (maybe will help you with Safari issue):
model: function() {
var that = this;
return new Ember.RSVP.Promise(function(resolve) {
that.store.findAll('service').then(function(services) {
resolve(services.filterBy('service-category-current', 'web'));
});
});
}