Related
I am modelling a boxing tournament.
Boxers and Fights have a many-to-many relationship:
A Boxer has many Fights
A Fight has many Boxers (exactly 2)
Here are the models in the schema
model Fight {
id Int #id #default(autoincrement())
name String
boxers BoxerFights[]
}
model Boxer {
id Int #id #default(autoincrement())
name String #unique
fights BoxerFights[]
}
model BoxerFights {
boxer Boxer #relation(fields: [boxerId], references: [id])
boxerId Int
fight Fight #relation(fields: [fightId], references: [id])
fightId Int
##id([boxerId, fightId])
}
When creating a boxer I use the fight's name and the 2 boxer ids:
const fight = await prisma.fight.create({
data: {
name,
boxers: {
createMany: {
data: [
{
boxerId: boxerId1,
},
{
boxerId: boxerId2,
},
],
},
},
},
})
How would I update the fight if a boxer needed to be changed? Something like this? I'm not sure if I use update and set
const fight = await prisma.fight.update({
data: {
name: newName,
boxers: {
set: {
data: [
{
boxerId: newBoxerId1,
},
{
boxerId: newBoxerId2,
},
],
},
},
},
})
Here you go an example how to do that:
const { PrismaClient } = require('#prisma/client')
const prisma = new PrismaClient()
const saveData = async () => {
const boxer1 = await prisma.boxer.create({
data: {
name: 'Boxer1',
},
})
const boxer2 = await prisma.boxer.create({
data: {
name: 'Boxer2',
},
})
const fight = await prisma.fight.create({
data: {
name: 'Fight 1',
boxers: {
createMany: {
data: [
{ boxerId: boxer1.id },
{ boxerId: boxer2.id },
]
},
}
},
select: {
id: true,
name: true,
boxers: {
select: {
boxer: {
select: {
name: true,
}
}
}
}
}
})
console.log(JSON.stringify(fight, null, 2))
const boxer3 = await prisma.boxer.create({
data: {
name: 'Boxer3',
},
})
const fightUpdated = await prisma.fight.update({
where: {
id: fight.id
},
data: {
boxers: {
createMany: {
data: [
{ boxerId: boxer3.id },
]
},
deleteMany: {
OR: [
{ boxerId: { equals: boxer1.id } },
]
}
}
},
select: {
name: true,
boxers: {
select: {
boxer: {
select: {
name: true,
}
}
}
}
}
})
console.log(JSON.stringify(fightUpdated, null, 2))
}
saveData()
In the update you have to remove the previous boxer and the new one :)
I have two tables:
const attr = {
name: {
type: DataTypes.STRING,
},
};
const Tags = createModel('Tags', attr, {});
and:
const attr = {
tagId: {
type: DataTypes.INTEGER,
references: { model: 'Tags', key: 'id' },
}
}
const Client = createModel('Client', attr, {})
Client.belongsTo(Tag, { foreignKey: 'tagId', as: 'tags' });
and my query is this:
const clientCount = await Client.findAll({
include: [ { model: Tags, as: 'tags' } ],
attributes: { exclude: 'tagId' }
});
and this is my response:
{
"id": 1,
"createdAt": "2020-01-20T00:00:00.000Z",
"updatedAt": "2020-01-22T00:00:00.000Z",
"tags": {
"id": 1,
"name": "New tag",
"createdAt": "2020-01-20T00:00:00.000Z",
"updatedAt": "2020-01-20T00:00:00.000Z"
}
}
but I want my tags to be an array, so I guest I have to define a one to many association, but everything I tried so far failed.
What I want is tags to be an array, where I can add multiple tag objects:
{
"id": 1,
"createdAt": "2020-01-20T00:00:00.000Z",
"updatedAt": "2020-01-22T00:00:00.000Z",
"tags": [
{
"id": 1,
"name": "New tag",
"createdAt": "2020-01-20T00:00:00.000Z",
"updatedAt": "2020-01-20T00:00:00.000Z"
}
]
}
Method1
We need new model as Client_Tag
const attr = {
clientId: {
type: DataTypes.INTEGER,
},
tagId: {
type: DataTypes.INTEGER,
},
};
const Client_Tag = createModel('Client_Tag', attr, {});
Client.belongsToMany(Tag, {
foreignKey: 'clientId',
otherKey: 'tagId',
through: models.Client_Tag,
as: 'tags'
});
const clientCount = await Client.findAll({
include: [ { model: Tags, as: 'tags' } ],
attributes: { exclude: 'tagId' }
});
Method2
const attr = {
name: {
type: DataTypes.STRING,
},
clientId: { // need clientId in tag model, and remove 'tagId' from client model
type: DataTypes.INTEGER,
}
};
const Tags = createModel('Tags', attr, {});
Client.belongsToMany(Tag, { foreignKey: 'tagId', as: 'tags' });
Is this schema valid in relational-pouch (especially the relations between obj and objList):
let schema = [
{
singular: 'obj', plural: 'objs', relations: {
'objList': { belongsTo: 'objList' },
'attributesEditable': { belongsTo: 'attributesEditable' },
'attributesViewable': { belongsTo: 'attributesViewable' },
},
},
{
singular: 'objList', plural: 'objLists', relations: {
'objs': { hasMany: 'obj' },
'obj': { belongsTo: 'obj' },
},
},
{
singular: 'attributesEditable', plural: 'attributesEditables', relations: {
'obj': { belongsTo: 'obj' },
},
},
{
singular: 'attributesViewable', plural: 'attributesViewables', relations: {
'obj': { belongsTo: 'obj' },
},
},
];
What I want:
My App starts with an entry point which is an obj and this has one objList with many obj in it and so on.
You have one realtion between objList and obj, and should declare it in both parts. But in objList declared two relations. Try this code:
[...]
{
singular: 'obj', plural: 'objs', relations: {
'objList': { belongsTo: 'objList' },
'attributesEditable': { belongsTo: 'attributesEditable' },
'attributesViewable': { belongsTo: 'attributesViewable' },
},
},
{
singular: 'objList', plural: 'objLists', relations: {
'objs': { hasMany: 'obj' }
},
[...]
I have documents of the form
challenge:
{
"name": "challenge by abdul",
"created_user_id": "1",
"game_id": "123",
"platform_id": "9857",
"amount": 30
}
game:
{
"_id": "auto_generated",
"name": "NFS",
"version": "3",
}
platform:
{
"_id": "auto_generated",
"name": "ps2",
"version": "sami"
}
I want to perform join query in sails and want result in below format
{
"name": "challenge by abdul",
"created_user_id": "1",
"game_id": "123",
"game_name":"NFS",
"platform_name": "ps2",
"platform_id": "9857",
"amount": 30
}
There is no join in Sails but populate. So you need make associations between models and populate them. Example:
// api/models/Platform.js
module.exports = {
attributes: {
name: {
type: 'string'
},
version: {
type: 'string'
},
game: {
model: 'Game',
via: 'platform'
}
}
};
// api/models/Game.js
module.exports = {
attributes: {
name: {
type: 'string'
},
version: {
type: 'string'
},
platform: {
model: 'Platform',
via: 'game'
}
}
};
You can write following code then:
// api/controllers/AnyController.js
module.exports = {
index: function(req, res) {
Game
.findOne({name: 'MY_GAME'})
.populate('platform')
.then(function(game) {
console.log(game); // Game model
console.log(game.platform); // Platform model
return game;
})
.then(res.ok)
.catch(res.negotiate);
}
};
I want to read json data from file - content of the json file shown below
{
"form": {
"fields" : [
{
"field":"textfield",
"name": "username",
"constrain": "5-10",
"value": ""
},
{
"field":"textfield",
"name": "password",
"constrain": "5-10",
"value": ""
},
{
"field":"datepickerfield",
"name": "Birthday",
"constrain": "5-10",
"value": "new Date()"
},
{
"field":"selectfield",
"name": "Select one",
"options":[
{"text": "First Option", "value": 'first'},
{"text": "Second Option", "value": 'second'},
{"text": "Third Option", "value": 'third'}
]
},
]
}
}
Model
Ext.define('dynamicForm.model.Form', {
extend: 'Ext.data.Model',
config: {
fields: [
{name: 'field', type: 'string'},
{name: 'name', type: 'string'},
{name: 'constrain', type: 'string'},
{name: 'value', type: 'string'}
],
hasMany: {model: 'dynamicForm.model.SelectOption', name: 'options'}
}
});
Ext.define('dynamicForm.model.SelectOption', {
extend: 'Ext.data.Model',
config: {
fields: [
{name: 'text', type: 'string'},
{name: 'value', type: 'string'}
]
}
});
store
Ext.define('dynamicForm.store.FormStore', {
extend : 'Ext.data.Store',
storeId: 'formStore',
config : {
model : 'dynamicForm.model.Form',
proxy : {
type : 'ajax',
url : 'form.json',
reader : {
type : 'json',
rootProperty : 'form.fields'
}
},
autoLoad: true
}
});
This what i tried so for.
var fromval = Ext.create('dynamicForm.store.FormStore');
fromval.load(function (){
console.log(fromval);
// i added register view which having form panel with id "testForm"
Ext.Viewport.add({
xtype : 'register'
});
for(i=0; i< fromval.getCount(); i++) {
console.log("------");
Ext.getCmp('testForm').add({
xtype: fromval.getAt(i).data.field,
label: fromval.getAt(i).data.name,
value: fromval.getAt(i).data.value,
options: [
{text: "First Option", value: "first"},
{text: "Second Option", value: "second"},
{text: "Third Option", value: "third"}
]
});
}
});
two text fileds and date are woking good, but i don't know how to get options for select field from store, just heard coded now.
over all Based on the above json data, i need to create sencha form dynamically.
Better to follow MVC structure:
Create a model:
Ext.define('MyApp.model.FormModel', {
extend: 'Ext.data.Model',
config: {
fields: ["field","name"]
}
});
A store with proxy:
Ext.define('MyApp.store.FormStore',{
extend: 'Ext.data.Store',
config:
{
model: 'MyApp.model.FormModel',
autoLoad:true,
proxy:
{
type: 'ajax',
url : 'FormData.json', //Your file containing json data
reader:
{
rootProperty:'form.fields'
}
}
}
});
The formData.json file:
{
"form": {
"fields" : [
{
"field":"textfield",
"name": "username"
},
{
"field":"textfield",
"name": "password"
},
]
}
}
And then use the FormStore to fill the form data as you need.
Ext.define('MyApp.view.LoginPage', {
extend: 'Ext.form.Panel',
config: {
items:{
xtype:'fieldset',
layout:'vbox',
items:[{
flex:1,
xtype:'textfield',
id:'namefield',
placeHolder:'Username'
},{
flex:1,
xtype:'passwordfield',
id:'passwordfield',
placeHolder:'Password'
}]
},
listeners:{
painted:function()
{
var store=Ext.getStore('FormStore');
while(!store.isLoaded())
{
console.log("loading...");
}
var record=store.getAt(0);
Ext.getCmp('namefield').setValue(record.data.name);
Ext.getCmp('passwordfield').setValue(record.data.password);
}
}
}
});
{
"data":[
{
"xtype":"textfield",
"title":"UserName",
"name": "username"
},
{
"xtype":"textfield",
"title":"password",
"name": "password"
},
{
"xtype":"textfield",
"title":"phone no",
"name": "birthday"
},
{
"xtype":"textarea",
"title":"address",
"name": "address"
}
]
}
Ext.define('dynamicForm.model.FormModel', {
extend: 'Ext.data.Model',
fields: ['field', 'name']
});
Ext.define('dynamicForm.store.FormStore', {
extend : 'Ext.data.Store',
model : 'dynamicForm.model.FormModel',
proxy :
{
type : 'ajax',
url : 'data/user.json',
reader :
{
type : 'json',
rootProperty:'data'
},
autoLoad: true
}
});
Ext.define('dynamicForm.view.DynaForm',{
extend:'Ext.form.Panel',
alias:'widget.df1',
items:[]
});
Ext.application({
name:'dynamicForm',
appFolder:'app',
controllers:['Users'],
launch:function(){
Ext.create('Ext.container.Viewport',{
items:[
{
xtype:'df1',
items:[]
}
]
});
}
});
Ext.define('dynamicForm.controller.Users',{
extend:'Ext.app.Controller',
views:['DynaForm'],
models:['FormModel'],
stores:['FormStore'],
refs:[
{
ref:'form1',
selector:'df1'
}
],
init:function(){
console.log('in init');
this.control({
'viewport > panel': {
render: this.onPanelRendered
}
});
},
onPanelRendered: function() {
var fromval=this.getFormStoreStore();
var form=this.getForm1();
fromval.load({
scope: this,
callback: function(records ,operation, success) {
Ext.each(records, function(rec) {
var json= Ext.encode(rec.raw);
var response=Ext.JSON.decode(json);
for (var i = 0; i < response.data.length; i++) {
form.add({
xtype: response.data[i].xtype,
fieldLabel: response.data[i].title,
name: response.data[i].name
});
}
//form.add(Ext.JSON.decode(json).data);
form.doLayout();
});
}
});
}
});
It will be done automatically if you insert it into any extjs component content :
var jsonValues = "{
"form": {
"fields" : [
{
"field":"textfield",
"name": "username"
},
{
"field":"textfield",
"name": "password"
},
]
}
}";
var panel = new Ext.Panel({
id : 'myPanel',
items : [jsonValues]
});
panel.show();