sequelize eager loading for join - join

Battery.belongsTo(TagType, { constraints: true, onDelete: "CASCADE" });
Tag.belongsTo(TagType, { constraints: true, onDelete: "CASCADE" });
const battery = sequelize.define("Battery", {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
voltage: {
type: Sequelize.INTEGER,
allowNull: false,
},
percetange: {
type: Sequelize.INTEGER,
allowNull: false,
},
});
const tag = sequelize.define("Tag", {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
name: {
type: Sequelize.STRING,
allowNull: false,
unique: true,
},
battery: {
type: Sequelize.INTEGER,
allowNull: true,
},
});
//api
const percetangeAndTags = [];
const tags = await Tag.findAll({
include: [
{
model: TagType,
attributes: ["name"],
},
],
});
error.catchError("notFound", tags);
await Promise.all(
tags.map(async (tag) => {
const batteryVoltageValue = await Battery.findOne({
where: {
tagTypeId: tag.tagTypeId,
voltage: { [Op.lte]: tag.battery },
},
attributes: [
[Sequelize.fn("max", Sequelize.col("voltage")), "max"],
],
});
const battery = await Battery.findOne({
where: {
tagTypeId: tag.tagTypeId,
voltage: batteryVoltageValue.dataValues.max,
},
});
percetangeAndTags.push({
id: tag.id,
name: tag.name,
tag_type: tag.tag_type.name,
percetange: battery?.percetange,
});
})
);
res.status(200).json(percetangeAndTags);
How can I write this code in the most efficient way?
Because the explanation is short, it doesn't accept the question, so I wrote a poem instead of randomly throwing it.
Keleci bilen kişinin yüzünü ağ ede bir söz
Sözü pişirip diyenin işini sağ ede bir söz
Söz ola kese savaşı söz ola bitire başı
Söz ola ağılı aşı bal ile yağ ede bir söz

Related

TypeORM does not save relations

I have the following entity which I want to save:
#Entity('approvals')
export class Approval {
#PrimaryGeneratedColumn()
id: string;
#ManyToOne(type => Task, task => task.approvals, {nullable: false, onDelete: 'CASCADE', lazy: true})
task: Promise<Task> | Task;
#ManyToOne(type => User, user => user.approvals, {nullable: false, onDelete: 'CASCADE', lazy: true})
user: Promise<User> | User;
#Column({ type: 'enum', enum: ApprovalState, default: ApprovalState.None })
state: ApprovalState;
constructor(partialApproval: Partial<Approval>) {
Object.assign(this, partialApproval);
}
}
If I want to save an entity which looks like (copied while debugging):
[
{
"task": {
"id": "2",
"name": "task1",
"type": "type1",
"neededTimeSeconds": 0,
"factor": 1,
"userId": "1",
"periodStart": "2019-01-01",
"periodEnd": "2019-01-31",
"done": true,
"__user__": {
"id": "1",
"username": "user1",
"password": "$2b$10$SBPIVm9p8L4YkpiUVJ.mpedIgWi5Je6MuWTM7IvgMdyhr27JYM0OG",
"credits": 0,
"gravatarHash": null
},
"__has_user__": true
},
"user": {
"id": "2",
"username": "shouldHaveApprovalUser1",
"password": "password1",
"credits": 0,
"gravatarHash": null
}
},
{
"task": {
"id": "2",
"name": "task1",
"type": "type1",
"neededTimeSeconds": 0,
"factor": 1,
"userId": "1",
"periodStart": "2019-01-01",
"periodEnd": "2019-01-31",
"done": true,
"__user__": {
"id": "1",
"username": "user1",
"password": "$2b$10$SBPIVm9p8L4YkpiUVJ.mpedIgWi5Je6MuWTM7IvgMdyhr27JYM0OG",
"credits": 0,
"gravatarHash": null
},
"__has_user__": true
},
"user": {
"id": "3",
"username": "shouldHaveApprovalUser2",
"password": "password1",
"credits": 0,
"gravatarHash": null
}
}
]
Then calling repository.save() with the above array, I get:
null value in column "taskId" violates not-null constraint
Although there is clearly the id defined in each task.
This is the Task entity class:
#Entity('tasks')
export class Task {
#PrimaryGeneratedColumn({ type: 'bigint' })
id: string;
#Column({ length: 30 })
name: string;
#Column({ default: 'help' })
type: string;
#Column({ name: 'needed_time', type: 'int', nullable: true })
neededTimeSeconds: number;
#Column({ type: 'int', default: 1 })
factor: number;
#ManyToOne(type => User, { nullable: true, lazy: true })
#JoinColumn({ name: 'user_id' })
user: Promise<User>;
#Column({ name: 'user_id' })
#RelationId((task: Task) => task.user)
userId: string;
#Column({ name: 'period_start', type: 'date', default: new Date() })
periodStart: string;
#Column({ name: 'period_end', type: 'date', default: new Date() })
periodEnd: string;
#Column({ type: 'boolean', default: false })
done: boolean;
#OneToMany(type => Approval, approval => approval.task, { nullable: true, lazy: true })
approvals: Promise<Approval[]>;
#OneToMany(type => TaskMessage, taskMessage => taskMessage.task, { cascade: ['remove'], lazy: true })
messages: Promise<TaskMessage[]>;
constructor(partialTask: Partial<Task>) {
Object.assign(this, partialTask);
}
}
Can anyone tell me why the relation task is not going to be assigned/saved?
I think you are missing cascade: true for the options of the relations, this should be set on the loose side of the relation (OneToMany) - check the example
You can use Typeorm's cascades for this: https://orkhan.gitbook.io/typeorm/docs/relations#cascades
Setting the cascade property in your relationship decorator changes the behavior of typeorm's .save() method.
#OneToMany(type => Approval, approval => approval.task, {
nullable: true,
lazy: true,
cascade: ["insert", "update", "remove"]
})
approvals: Approval[];
With cascades enabled, you can insert, update or remove related entities with a single call to .save().
To create a new approval and insert task:
await this.approvalsEntity.save({ ...approvalData, task: taskData })
To update a task on a pre-existing approval:
await this.approvalsEntity.save({
id: approvalId,
task: { id: taskId, ...approvalUpdate }
})

How to use data from Model to bind as kendo datasource

i have an empty div that i want to initialize into a kendo grid using data from Model..it should be something like the following but i am unable to load data
$("#mapsDiv").kendoGrid({
sortable: true,
dataSource: {
transport: {
read:"/Home/About",
dataType: "odata"
},
pageSize: 5
},
pageable: true,
resizable: true,
columnMenu: true,
scrollable:true,
navigatable: true,
editable: "incell"
});
About.cshtml
#model List<KendoExample.Entities.ShortStudent>
<div class="row">
<div class="col-md-12 table-responsive" id="mapsDiv">
</div>
My Home Controller is as follows
List<ShortStudent> students = new List<ShortStudent>();
ShortStudent student1 = new ShortStudent();
student1.birthdate = new DateTime(1999, 4, 30);
student1.classname = "1B";
student1.firstname = "Fredie";
student1.surname = "Fletcher";
student1.studentid = 1;
ShortStudent student2 = new ShortStudent();
student2.birthdate = new DateTime(2010, 5, 4);
student2.classname = "1B";
student2.firstname = "Lee";
student2.surname = "Hobbs";
student2.studentid = 2;
students.Add(student1);
students.Add(student2);
return View(students);
I have seen examples using json but not odata...
Also, there are examples to use it like
#(Html.Kendo().Scheduler<MeetingViewModel>()
.Name("scheduler")
.Editable(false)
.DataSource(ds => ds
.Custom()
.Batch(true)
.Schema(schema => schema
.Model(m =>
{
m.Id(f => f.MeetingID);
m.Field("title", typeof(string)).DefaultValue("No title").From("Title");
m.Field("start", typeof(DateTime)).From("Start");
m.Field("end", typeof(DateTime)).From("End");
m.Field("description", typeof(string)).From("Description");
m.Field("recurrenceID", typeof(int)).From("RecurrenceID");
m.Field("recurrenceRule", typeof(string)).From("RecurrenceRule");
m.Field("recurrenceException", typeof(string)).From("RecurrenceException");
m.Field("isAllDay", typeof(bool)).From("IsAllDay");
m.Field("startTimezone", typeof(string)).From("StartTimezone");
m.Field("endTimezone", typeof(string)).From("EndTimezone");
}))
.Transport(new {
//the ClientHandlerDescriptor is a special type that allows code rendering as-is (not as a string)
read = new Kendo.Mvc.ClientHandlerDescriptor() {HandlerName = "customRead" }
})
)
)
which i am unable to understand/implement so please ignore this kind of a solution.
Currently i see a grid footer that says (1 - 2 of 4852 items) without any header or content(datarows) on my screen. What am I doing wrong?
UPDATE
var dataSource = new kendo.data.DataSource(
{
transport: {
read: {
url: '#Url.Action("About", "Home")',
contentType: "application/json",
dataType: "json"
}
},
schema: {
model: {
fields: {
firstname: { type: "string" },
surname: { type: "string" },
birthdate: { type: "date" },
classname: { type: "string" }
}
}
},
type: "json",
serverPaging: false,
serverFiltering: true,
serverSorting: false
}
);
$("#mapsDiv")
.kendoGrid(
{
sortable: true,
dataSource: {
transport: {
read: dataSource
},
pageSize: 2
},
pageable: true,
resizable: false,
columnMenu: true,
scrollable:true,
navigatable: true,
editable: "incell",
columns:[{
field: "firstname",
},{
field: "surname",
},{
field: "classname",
},{
field: "age",
}]
});
HomeController
public ActionResult About()
{
....
return View(students);
}
Now the grid with header is there but no data is present..
If i change action to json, it returns plain json on the page
public ActionResult About()
{
....
return Json(students, JsonRequestBehavior.AllowGet);
}
Have you tried adding the fields to the grid?
$("#mapsDiv")
.kendoGrid(
{
sortable: true,
dataSource: {
transport: {
read:"/Home/About",
dataType: "odata"
},
pageSize: 5
},
columns: [
{
field: "classname",
title: "Class Name"
},
{
field: "firstname",
title: "First name"
},
{
field: "surname",
title: "Last name"
}
],
pageable: true,
resizable: true,
columnMenu: true,
scrollable:true,
navigatable: true,
editable: "incell"
});
I just visit demo of telerik. Try following. Hope to help, my friend. Or you can visit this link to refer more: http://demos.telerik.com/kendo-ui/grid/remote-data-binding.
$("#mapsDiv")
.kendoGrid(
{
sortable: true,
dataSource: {
transport: {
read:"/Home/About",
dataType: "odata"
},
pageSize: 5
},
schema: {
model: {
fields: {
studentid: { type: "number" },
birthdate : { type: "date" },
classname : { type: "string" },
firstname : { type: "date" },
surname : { type: "string" }
}
}
},
pageable: true,
resizable: true,
columnMenu: true,
scrollable:true,
navigatable: true,
editable: "incell"
});
So here is what i found what should have been straight forward :)
var values = #Html.Raw(Json.Encode(#Model));
$("#MapDetails")
.kendoGrid(
{
sortable: true,
dataSource: {
data:values,
pageSize: 2
},
pageable: true,
resizable: false,
columnMenu: true,
scrollable:true,
navigatable: true,
editable: "incell",
columns:[{
field: "firstname",
},{
field: "surname",
},{
field: "classname",
},{
field
: "age",
}]
});

Bind data to grid after page load MVC

I have problem here.With kendo grid i'm loading data from some action in controller.But in the last column i have link which should fire another action in same controller.When i delete this piece of code
type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("ListFinances", "Jobs"))",
type: "POST",
dataType: "json",
data: additionalData
},
},
schema: {
data: "Data",
total: "Total",
errors: "Errors"
},
last column is working perfect,bit when is present this piece of code, last column is not working>please here some help, i;m new to mvc.Below is the code:
$("#jobs-grid").kendoGrid({
dataSource: {
data: #Html.Raw(JsonConvert.SerializeObject(Model.FinishedJobs)),
schema: {
model: {
fields: {
JobNumber: { type: "string" },
CustomerId: { type: "number" },
JobCount: { type: "number" },
JobYear: { type: "number" },
Status: { type: "number" },
Position: { type: "number" },
Finished: { type: "boolean" },
HasInvoice: { type: "boolean" },
}
}
},
type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("ListFinances", "Jobs"))",
type: "POST",
dataType: "json",
data: additionalData
},
},
schema: {
data: "Data",
total: "Total",
errors: "Errors"
},
error: function(e) {
display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
},
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
//dataBound: onDataBound,
columns: [
#*{
field: "Status",
title: "Status",
template: '#= Status #'
},*#
{
field: "JobNumber",
title: "jobNumber",
template: '#= JobNumber #'
},
{
field: "CustomerId",
title: "Customer",
template: '#= Customer.Name #'
},
{
field: "Id",
title: "Id"
},
#*{
field: "ShortDesc",
title: "ShortDesc"
},*#
{
field: "DateCompletition",
title: "DateCompletition"
},
{
field: "Id",
title: "#T("Common.Edit")",
width: 130,
template: 'Edit'
}
],
pageable: {
refresh: true,
pageSizes: [5, 10, 20, 50]
},
editable: {
confirmation: false,
mode: "inline"
},
scrollable: false,
// sortable: true,
// navigatable: true,
// filterable: true,
// scrollable: true,
selectable: true
});
});
</script>
It seems you want to add a command to the grid, The way to add a command as described here is as follows
var grid = $("#jobs-grid").kendoGrid({
dataSource: {
pageSize: 20,
data: #Html.Raw(JsonConvert.SerializeObject(Model.FinishedJobs)),
},
pageable: true,
height: 550,
columns: [
{ field: "JobNumber", title: "JobNumber", width: "140px" },
{ field: "CustomerId", title: "Customer", width: "140px" },
{ field: "Id", title:"Id" },
{ field: "DateCompletition", title:"DateCompletition" },
{ command: { text: "Edit",
click: function(e){
// here you can add your code
}},
title: " ",
width: "180px" }]
}).data("kendoGrid");
You might have a look on the documentation of the kendo grid here
Hope this will help you

kendo ui Grid "Popup mode" ,Edit And Delete Button, Not firing the Controller Action

This is My view with kendo ui grid, It's Read function firing just fine, but the problem just begins when I want to update,
The update Function in my controller Not even Firing,
<script>
$(document).ready(function () {
var dataSource = {
transport: {
type: "json",
read: {
url: "#Html.Raw(Url.Action("CommentList", "Comment"))",
type: "POST",
dataType: "json"
},
update: {
url: "#Html.Raw(Url.Action("CommentUpdate", "Comment"))",
type: "POST",
dataType: "json"
},
destroy: {
url: "#Html.Raw(Url.Action("CommentDelete", "Comment"))",
type: "POST",
dataType: "json"
}
},
schema: {
data: "Data",
total: "Total",
errors: "Errors",
model: {
id: "Id",
fields: {
Id: { type: "number" },
ProductName: { editable: false, type: "string"},
ProductPicture: { editable: false, type: "string"},
Text: { editable: false, type: "string"},
AdminConfirm: { editable: true, type: "boolean", validation: { required: true } }
}
}
},
requestEnd: function (e) {
if (e.type === "create" || e.type === "update") {
this.read();
}
},
error: function (e) {
alert("something wrong!");
// Cancel the changes
this.cancelChanges();
},
pageSize: 15,
serverPaging: true,
serverFiltering: true,
serverSorting: true
};
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: {
refresh: true,
pageSizes: [10, 15, 20, 30, 50]
},
height: 550,
columns: [
{
field: "ProductName",
title: "product name",
width: "90px"
},
{
field: "ProductPicture",
title: "picture",
width: "100px",
},
{
field: "Text",
title: "comment",
width: "180px"
},
{
field: "AdminConfirm",
title: "adminconfirm",
width: "70px",
},
{
command: [
{
name: "edit" , text: { // sets the text of the "Edit", "Update" and "Cancel" buttons
edit: "edit",
update: "update",
cancel: "cancel"
}
}
],
title: " ", width: "250px"
}
],
editable : {
mode : "popup",
window : {
title: "confirmation form"
}}
});
});
</script>
</div>
This is My first line of update Function
[HttpPost]
public ActionResult CommentUpdate(DataSourceRequest request, CommentViewModel comment)
Anybody Know Why?
Thanx in Advance

JQGrid is not loading data in MVC 5?

I am using jqgrid and table is working correctly. But no data is loading and it continuesly displaying "loading...". It worked correctly but i maybe due to some reason it is not working now.
public JsonResult GetDetails()
{
Database1Entities db = new Database1Entities();
var jsondata = new
{
total = 1,
page = 1,
records = db.Employees.ToList().Count.ToString(),
rows = db.Employees.Select(a => new {
a.Id,a.Name,a.Designation,a.Address,a.Salary
})
};
return Json(jsondata, JsonRequestBehavior.AllowGet);
}
JQGrid function is below:
$(document).ready(function () {
$("#Grid").jqGrid({
url: '/Home/GetDetails',
datatype: 'json',
myType: 'GET',
colNames: ['id','Name', 'Designation', 'Address', 'Salary'],
colModel: [
{ key: false, name: 'Id', index: 'Id', },
{ key: false, name: 'Name', index: 'Name', editable: true },
{ key: false, name: 'Designation', index: 'Designation', editable: true },
{ key: false, name: 'Address', index: 'Address', editable: true },
{ key: false, name: 'Salary', index: 'Salary', editable: true }
],
jsonReader: {
root: 'rows',
page: 'page',
total: 'total',
records: 'records',
id: '0',
repeatitems: false
},
pager: $('#pager'),
rowNum: 10,
rowList: [10, 20, 30],
width: 600,
viewrecords: true,
multiselect: true,
sortname: 'Id',
sortorder: "desc",
caption: 'Employee Records',
loadonce: true,
}).navGrid('#pager', { edit: true, add: true, del: true },
{
zIndex: 100,
url: '/Home/Edit',
closeOnEscape: true,
closeAfterEdit: true,
recreateForm: true,
afterComplete: function (response) {
if (response.responseText)
{
alert(response.responseText);
}
}
},
{
zIndex: 10,
url: '/Home/Add',
closeOnEscape: true,
closeAfterEdit: true,
recreateForm: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
},
{
zIndex: 100,
url: '/Home/Delete',
closeOnEscape: true,
closeAfterEdit: true,
recreateForm: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
}
);
});
If i add something, it works and data is inserted into database but the main problem is not data is shown in JQGrid. What is the problem?

Resources