How to loop through JSON Object in vue js - laravel

I am working on vue.js and backend is laravel. I am new to these technologies.
I am trying to display data in parent and child rows in a table base on vue material syntax.
My Laravel controlller function contains the code
$tasks = Task::select('tasks_status', DB::raw("group_concat(CONCAT('{\"id\":\"',id,'\",\"name\":\"',name,'\"}') ) as subrow"))
->where('tasks_status', '<>', "Sent Tasks")
->whereNull('user_id')
->orderBy('id', 'desc')
->groupBy('tasks_status')
->get();
I am trying to get data grouped by task_status. For each task status there are multiple rows.
My JSON is like below -
[
{
"tasks_status": "Completed Task",
"subrow": "{\"id\":\"4\",\"name\":\"d1\"}"
},
{
"tasks_status": "My Tasks",
"subrow": "{\"id\":\"2\",\"name\":\"b1\"},{\"id\":\"7\",\"name\":\"g1\"}"
}
]
Online JSON Parser validates it.
in Vue Front end I try to display this JSON data using 2 for loops Like below
<md-table v-model="searched" md-sort="name" md-sort-order="asc" md-fixed-header class="table-sort">
<md-table-toolbar>
<div class="md-toolbar-section-start">
<h1 class="md-title">Tasks</h1>
</div>
<md-field md-clearable class="md-toolbar-section-end">
<label for="Tasks">Tasks</label>
<md-select v-model="fieldsSearchTerm.searchTermForDataTable" name="search" id="search" #input="searchOnTable" >
<md-option value="">All Tasks</md-option>
<md-option value="My Tasks">My Tasks</md-option>
<md-option value="Organization Tasks"
>Organization Tasks</md-option
>
<md-option value="Received Tasks"
>Received Tasks</md-option
>
<md-option value="Completed Task"
>Completed Task</md-option
>
<md-option value="Incomplete Tasks"
>Incomplete Tasks</md-option
>
<md-option value="Sent Tasks">Sent Tasks</md-option>
</md-select>
</md-field>
<md-field md-clearable class="md-toolbar-section-end">
<b-button class="btn btn-danger modal-btn" block #click="changeStatusToDone">Done</b-button>
</md-field>
</md-table-toolbar>
<md-table-empty-state
md-label="No data found">
</md-table-empty-state>
<md-table-row slot="md-table-row" v-for="rowHeading in searched" >
<md-table-cell md-label="Task Name" md-sort-by="name">{{ rowHeading.tasks_status }}</md-table-cell>
<md-table-cell md-label="Task Status" md-sort-by="tasks_status"></md-table-cell>
<md-table-cell md-label="Due Date" md-sort-by="due_date"></md-table-cell>
<md-table-cell md-label="Priority" md-sort-by="priority"></md-table-cell>
<md-table-cell md-label="Actions" md-sort-by="">
</md-table-cell>
</md-table-row>
<md-table-row slot="md-table-row" v-for="subRowElements in rowHeading.subrow">
<md-table-cell md-label="" md-sort-by="" >
</md-table-cell>
<md-table-cell colspan=4 md-label="Task Name" md-sort-by="name">hi {{ subRowElements }}</md-table-cell>
</md-table-cell>
</md-table-row>
</md-table>
In My JS I have code like this below
import Cookies from 'js-cookie'
import axios from "axios"
import Vue from 'vue'
import VueResource from 'vue-resource'
import Form from 'vform'
const toLower = text => {
return text.toString().toLowerCase()
}
const searchByName = (items, term) => {
if (term) {
return items.filter(item => toLower(item.tasks_status).includes(toLower(term)))
}
return items
}
export default {
name: 'TableSearch',
components: {
},
data() {
form: new Form({
tasks_statusUpdate: '',
nameUpdate: '',
priorityUpdate: '',
task_descriptionUpdate: '',
dueDateUpdate: '',
taskAssignedToUserUpdate: '',
_token: Cookies.get('token')
})
return {
goods: [],
fieldsUpdate: {
tasks_statusUpdate: "",
nameUpdate: "",
priorityUpdate: "",
task_descriptionUpdate: '',
dueDateUpdate: "",
taskAssignedToUserUpdate: "",
_token: Cookies.get('token'),
},
fieldsView: {
tasks_statusView: "",
nameView: "",
priorityView: "",
task_descriptionView: '',
dueDateView: "",
taskAssignedToUserView: "",
userNameView: "",
},
fieldsTaskDone: {
tasks_status: 1,
},
fieldsSearchTerm: {
searchTermForDataTable: '',
},
fieldsCheckBox: {
cboTaskName: true,
cboTaskStatus: true,
cboDueDate: true,
cboPriority: true,
},
isOpen: true,
rows: null,
allUsersUpdate: [],
searched: [],
rowHeading:[],
subRowElements:[],
users: [
{
id: 1,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 2,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 3,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 4,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 5,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 6,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 7,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 8,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 9,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 10,
name: "Shawna vishal",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
],
rows: [],
editing_record_id: 0,
view_record_id: 0,
checkedTaskIDs: [],
dynamicColumn: [],
}
},
methods: {
newUser () {
window.alert('Noop')
},
searchOnTable () {
this.makeGetRequest();
this.searched = searchByName(this.rows, this.search)
},
fnDynamicColumns: function(e){
if (e.target.checked) {
console.log(e.target.value)
}
},
check_task_id: function(e) {
if (e.target.checked) {
console.log(e.target.value)
}
},
changeStatusToDone () {
axios
.post("api/v1/tasks/"+this.checkedTaskIDs+"/complete",
this.fieldsTaskDone
)
.then(response => {
alert("Task Done!");
})
.catch(error => {
console.log(error);
});
this.makeGetRequest();
},
async makeGetRequest() {
console.log("makeGetRequest begin ");
var fnRows = [];
await axios.get('api/v1/tasks', {
params: {
searchTermForDataTable: this.fieldsSearchTerm.searchTermForDataTable
}
})
.then((response) => {
this.rows = response.data;
fnRows = response.data;
console.log("inside axios > makeGetRequest" + JSON.stringify(this.rows));
});
this.searched = this.rows
console.log("makeGetRequest later " + this.searched);
},
async getAllUsers() {
console.log("table > getAllUsers begin ");
await axios.get('api/v1/getallusers')
.then((response) => {
this.allUsersUpdate = response.data;
});
console.log("table > outside axios user11" + this.allUsersUpdate);
},
submitUpdateForm() {
console.log(this.fieldsUpdate);
console.log(Cookies.get('token'));
axios
.put("api/v1/tasks/"+this.editing_record_id,
this.fieldsUpdate
)
.then(response => {
alert("Task Updated!");
//this.fields = {};
})
.catch(error => {
console.log(error);
});
this.makeGetRequest();
console.log("ppppnnnnnn");
},
async getTask() {
await axios.get('api/v1/tasks/'+this.editing_record_id)
.then((response) => {
this.fieldsUpdate.tasks_statusUpdate = response.data[0].tasks_status;
this.fieldsUpdate.nameUpdate = response.data[0].name;
this.fieldsUpdate.taskAssignedToUserUpdate = response.data[0].user_id;
this.fieldsUpdate.priorityUpdate = response.data[0].priority;
this.fieldsUpdate.task_descriptionUpdate = response.data[0].task_description;
if(response.data[0].due_date !== null)
{
this.fieldsUpdate.dueDateUpdate = response.data[0].due_date;
}
console.log("getTask With Join" + JSON.stringify(response.data[0]));
});
console.log("getTask With Join" + JSON.stringify(this.fieldsUpdate));
},
showUpdateModal(id) {
this.editing_record_id = id;
this.getTask();
this.$bvModal.show('taskUpdateModal')
},
softDeleteTask(id) {
if(confirm("Are you sure, you want to delete, this task?")){
axios
.delete("api/v1/tasks/"+id)
.then(response => {
alert("Task Deleted!");
//this.fields = {};
})
.catch(error => {
console.log(error);
});
this.makeGetRequest();
}
},
async getTaskForView() {
await axios.get('api/v1/tasks/'+this.view_record_id)
.then((response) => {
this.fieldsView.tasks_statusView = response.data[0].tasks_status;
this.fieldsView.nameView = response.data[0].name;
this.fieldsView.taskAssignedToUserView = response.data[0].user_id;
this.fieldsView.priorityView = response.data[0].priority;
this.fieldsView.task_descriptionView = response.data[0].task_description;
this.fieldsView.dueDateView = response.data[0].due_date;
this.fieldsView.userNameView = response.data[0].userName;
});
console.log("getTask" + JSON.stringify(this.fieldsView));
},
showViewModal(id) {
this.view_record_id = id;
this.getTaskForView();
this.$bvModal.show('taskViewModal')
},
},
created () {
console.log("inside created()1");
this.makeGetRequest();
this.getAllUsers();
console.log("outside axios" + this.rows);
enter code here
console.log("inside created() 2");
},
mounted() {
console.log("inside mounted()")
},
}
Can Anybody suggests a way to get valid JSON from controller and display it with correct loops in vue.js page. Thanks in advance.

I think you should use something like this in your Laravel controller, and then it would be easier to use loop to output json
$tasks = Task::select('tasks_status', DB::raw("group_concat(CONCAT('{\"id\":\"',id,'\",\"name\":\"',name,'\"}') ) as subrow"))
->where('tasks_status', '<>', "Sent Tasks")
->whereNull('user_id')
->orderBy('id', 'desc')
->groupBy('tasks_status')
->get()->map(function ($e) {
$e->subrow = json_decode($e->subrow);
return $e;
});

Related

Return the wrong response if type of is number in the graphql

I tried to run the basic query in the graphql. But the below query is always return the no data if the typeof id is number. incase typeof id is string it returns the correct respone.
{
movie(id: 1) {
id
name
}
}
respone
{
"data": {
"movie": null
}
}
attached my code below
const graphql = require("graphql");
const _ = require("lodash");
const {
GraphQLObjectType,
GraphQLString,
GraphQLSchema,
GraphQLID,
GraphQLInt,
GraphQLList,
} = graphql;
const movies = [
{ name: "book1", genre: "Thriller", id: 1, directorId: 1 },
{ name: "book2", genre: "Horror", id: 2, directorId: 1 },
{ name: "book3", genre: "Historical", id: 3, directorId: 2 },
{ name: "book4", genre: "Thriller", id: 4, directorId: 1 },
{ name: "book5", genre: "Science Fiction", id: 5, directorId: 2 },
{ name: "book6", genre: "Horror", id: 6, directorId: 3 },
{ name: "book7", genre: "Romance", id: 7, directorId: 1 },
];
const directors = [
{ name: "directors1", age: "26", id: 1 },
{ name: "directors2", age: "36", id: 2 },
{ name: "directors3", age: "46", id: 3 },
];
const MovieType = new GraphQLObjectType({
name: "Movie",
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
genre: { type: GraphQLString },
director: {
type: DirectorType,
resolve: (parent, args) => {
return _.find(directors, { id: parent.directorId });
},
},
}),
});
const DirectorType = new GraphQLObjectType({
name: "Director",
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
age: { type: GraphQLInt },
movies: {
type: MovieType,
resolve: (parent, args) => {
return _.find(movies, { directorId: parent.id });
},
},
}),
});
const RootQuery = new GraphQLObjectType({
name: "RootQueryType",
fields: {
movie: {
type: MovieType,
args: { id: { type: GraphQLID } },
resolve(parent, args) {
console.log(args)
return _.find(movies, { id: args.id });
},
},
director: {
type: DirectorType,
args: {id: {type: GraphQLID}},
resolve(parent, args) {
return _.find(directors, {id: args.id})
}
},
movies: {
type: new GraphQLList(MovieType),
resolve() {
return movies;
},
},
directors: {
type: new GraphQLList(DirectorType),
resolve() {
return directors;
},
},
},
});
module.exports = new GraphQLSchema({
query: RootQuery,
});
not sure what I have missed.

data not match with response from axios vuejs

im new in vuejs
I have button to get detail data like this:
<button class="btn btn-sm btn-primary" title="Detail" #click="showDetail(task.id)"><span class="fa fa-eye"></span></button>
and the script like this
export default {
data(){
return {
tasks: [],
taskDetail: [],
categoryName: "",
typeName: "",
detailExist: false
}
},
created(){
this.getTasks()
},
methods: {
getTasks(){
axios.get("/task-lists/")
.then(res => {
this.tasks = res.data.data
})
},
showDetail(id){
this.detailExist = false
axios.get("/task-detail/"+id)
.then(res => {
console.log(res)
this.taskDetail = res.data.data
this.detailExist = true
this.collectCategory(this.taskDetail.category)
this.collectType(this.taskDetail.type)
}).catch(error => {
console.log(error)
})
},
startTask(id){
axios.post('/start-task', {id: id, status: 1})
.then(res => {
this.getTasks()
console.log(res.data)
})
},
finishDev(id){
axios.post('/finish-dev', {id: id, status: 2})
.then(res => {
this.getTasks()
})
},
collectCategory(val){
switch (val) {
case 2:
this.categoryName = 'Normal';
break;
case 3:
this.categoryName = 'Emergency';
break;
default:
this.categoryName = 'Standard';
break;
}
},
collectType(val){
switch (val) {
case 2:
this.typeName = 'New Feature';
break;
case 3:
this.typeName = 'Bug Fixing';
break;
default:
this.typeName = 'Revamp';
break;
}
}
}
}
But i got confuse because there is a difference between what i get in res in axios and response api if i see from browser > inspect > network. In browser i get like this
{
"data": {
"id": 1,
"task_no": "RFC123XYZ",
"task_name": "Task View",
"mandays": 2,
"start_date": "2021-10-12",
"status": 2,
"category": 2,
"type": 2,
"description": null,
"cycle": [],
}
}
but in axios i always get value 1 in "status" when i console.log(res).

How to send object with an object inside to server Vue.js 3

I need to send object to the server:
{
"id": "null",
"indexNumber": "1454",
"indexYear": "2021",
"firstName": "John",
"lastName": "Doe",
"email": "john#doe.com",
"address": "John Doe Street 1231",
"city": {
"postalCode": 10000,
"name": "New York"
} ,
"currentYearOfStudy": 1
}
when I use to test it from postman everything is fine, but when I try to send object "student" from frontend i got this error message "Cannot read property 'postalCode' of undefined:
Where do I need to define this property, or where to define object city, how to do this?
inserStudent() {
StudentService.insertStudent({
indexNumber: this.indexNumber,
indexYear: this.indexYear,
firstName: this.firstName,
lastName: this.lastName,
email: this.email,
address: this.address,
postalCode: this.city.postalCode,
name: this.city.name,
currentYearOfStudy: this.currentYearOfStudy
})
.then((response) => {
console.log("Student inserted!" + response);
addMessage({
message: "Student inserted!",
type: "success",
title: "STUDENT",
});
})
.catch((error) => {
addMessage({
message: "Insert was not successful:" + error,
type: "danger",
title: "Insert student",
});
});
}
Sorry I'm new to vue...
<template>
<div class="form-container m-4 col-6 col-md-8 col-sm-10 mx-auto" display-inline-block>
<h3 v-if="actionType === 'new'">New Student</h3>
<h3 v-else>Edit Student</h3>
<MyInputComponent
name="indexNumber"
label="Index Number"
v-model="indexNumber"
:vcomp="v$.indexNumber"
></MyInputComponent>
<MyInputComponent
name="indexYear"
label="Index Year"
v-model="indexYear"
:vcomp="v$.indexYear" >
</MyInputComponent>
<MyInputComponent
name="firstName"
label="First Name"
v-model="firstName"
:vcomp="v$.firstName"
>
</MyInputComponent>
<MyInputComponent
name="lastName"
label="Last Name"
v-model="lastName"
:vcomp="v$.lastName"
>
</MyInputComponent>
<MyInputComponent
name="email"
label="Email"
v-model="email"
:vcomp="v$.email"
>
</MyInputComponent>
<MyInputComponent
name="address"
label="Address"
v-model="address"
:vcomp="v$.address"
>
</MyInputComponent>
<MyInputComponent
name="postalCode"
label="Postal Code"
v-model="postalCode"
:vcomp="v$.postalCode"
>
</MyInputComponent>
<MyInputComponent
name="name"
label="City Name"
v-model="name"
:vcomp="v$.name"
>
</MyInputComponent>
<MyInputComponent
name="currentYearOfStudy"
label="Curent Year Of Study"
v-model="currentYearOfStudy"
:vcomp="v$.currentYearOfStudy"
>
</MyInputComponent>
<div class="d-flex flex-row-reverse">
<button class="btn btn-outline-primary" #click="saveStudent">Save</button>
</div>
</div>
</template>
<script>
import useValidate from "#vuelidate/core";
import {
required,
minLength,
maxLength,
email,
maxValue,
minValue,
} from "#vuelidate/validators";
import MyInputComponent from "#/components/inputs/MyInputControl.vue";
import StudentService from "#/services/StudentService.js";
import { addMessage } from "#/main.js";
export default {
components: { MyInputComponent },
props: {
studentId: {
type: String,
},
actionType: {
type: String,
},
},
created() {
if (this.studentId) {
StudentService.getStudent(this.studentId).then((response) => {
const student = response.data;
this.indexNumber = student.indexNumber;
this.indexYear = student.indexYear;
this.firstName = student.firstName;
this.lastName = student.lastName;
this.email = student.email;
this.address = student.address;
this.postalCode = student.city.postalCode;
this.name = student.city.name;
this.currentYearOfStudy = student.currentYearOfStudy;
});
}
},
data() {
return {
v$: useValidate(),
id:null,
indexNumber: "",
indexYear: "",
firstName: "",
lastName: "",
email: "",
address: "",
postalCode: "",
name: "",
currentYearOfStudy: null,
randomNumber:''
};
},
validations() {
return {
indexNumber: {
required,
minLength: minLength(4),
maxLength: maxLength(4),
},
indexYear: {
required,
minLength: minLength(4),
maxLength: maxLength(4),
},
firstName: {
required,
minLength: minLength(3),
maxLength: maxLength(30),
},
lastName: {
required,
minLength: minLength(3),
maxLength: maxLength(30),
},
email: {
required,
email,
},
address: {
required,
minLength: minLength(3),
},
postalCode:{
required,
minValue: minValue(9999),
maxValue: maxValue(100000),
},
name:{
required,
minLength: minLength(3),
maxLength: maxLength(30)
},
currentYearOfStudy: {
required,
minValue: minValue(1),
maxValue: maxValue(5),
},
};
},
methods: {
saveStudent() {
if (this.actionType && this.actionType === "new") {
this.inserStudent();
} else {
this.updateStudent();
}
},
inserStudent() {
StudentService.insertStudent({
indexNumber: this.indexNumber,
indexYear: this.indexYear,
firstName: this.firstName,
lastName: this.lastName,
email: this.email,
address: this.address,
postalCode: this.city.postalCode,
name: this.city.name,
currentYearOfStudy: this.currentYearOfStudy
})
.then((response) => {
console.log("Student inserted!" + response);
addMessage({
message: "Student inserted!",
type: "success",
title: "STUDENT",
});
})
.catch((error) => {
addMessage({
message: "Insert was not successful:" + error,
type: "danger",
title: "Insert student",
});
});
},
updateStudent() {
StudentService.editStudent({
id: this.studentId,
indexNumber: this.indexNumber,
indexYear: this.indexYear,
firstName: this.firstName,
lastName: this.lastName,
email: this.email,
address: this.address,
postalCode: this.city.postalCode,
name: this.city.name,
currentYearOfStudy: this.currentYearOfStudy,
})
.then((response) => {
console.log("Student inserted" + response);
addMessage({
message: "Student updated",
type: "success",
title: "STUDENT",
});
})
.catch((error) => {
addMessage({
message: "Update was not successful:" + error,
type: "danger",
title: "Update student",
});
});
},
},
};
</script>
You've postalCode and name are defined in data property without nesting them, so you could nest them to a city field when you want to send the request :
StudentService.insertStudent({
indexNumber: this.indexNumber,
indexYear: this.indexYear,
firstName: this.firstName,
lastName: this.lastName,
email: this.email,
address: this.address,
city:{
postalCode: this.postalCode,
name: this.name,
},
currentYearOfStudy: this.currentYearOfStudy
})

Using nested datatable in laravel and build my own json

I am using Nested-datatables (https://github.com/AndrejGajdos/nested-datatables) so I have to use JSON.
I want to pass JSON from the controller to ajax and then use it in order to create a nested table.
The problem is that I need the exact JSON format so I will not get "undefined" result.
This is the example of the JSON format that I need (like in the link above) :
var dataInJson = [
{
data: {
name: 'b1',
street: 's1',
city: 'c1',
departments: 10,
offices: 15
},
kids: [
{
data: {
department: 'HR',
supervisor: 'Isidor Bristol',
floor: 1,
employees: 15
},
kids: [
{
data: {
name: 'Klement Nikodemos',
phone: '+938462',
hire_date: 'January 1, 2010',
id: 3456
},
kids: []
},
{
data: {
name: 'Madhava Helmuth',
phone: '+348902',
hire_date: 'May 23, 2002',
id: 1234
},
kids: []
},
{
data: {
name: 'Andria Jesse',
phone: '456123',
hire_date: 'October 23, 2011',
id: 9821
},
kids: []
}
]
},
{
data: {
department: 'development',
supervisor: 'Jim Linwood',
floor: 2,
employees: 18
},
kids: [
{
data: {
name: 'Origenes Maxwell',
phone: '345892',
hire_date: 'February 1, 2004',
id: 6234
},
kids: []
}
]
},
{
data: {
department: 'testing',
supervisor: 'Zekeriya Seok',
floor: 4,
employees: 11
},
kids: []
}
]
},
{
data: {
name: 'b2',
street: 's10',
city: 'c2',
departments: 3,
offices: 10
},
kids: [
{
data: {
department: 'development',
supervisor: 'Gallagher Howie',
floor: 8,
employees: 24
},
kids: [
{
data: {
name: 'Wat Dakota'
},
kids: []
}
]
},
{
data: {
department: 'testing',
supervisor: 'Shirley Gayle',
floor: 4,
employees: 11
},
kids: []
}
]
},
{
data: {
name: 'b3',
street: 's3',
city: 'c3',
departments: 2,
offices: 1
},
kids: [
{
data: {
department: 'development'
},
kids: [
{
data: {
name: 'Wat Dakota'
},
kids: []
}
]
},
{}
]
},
{
data: {
name: 'b4',
city: 'c4'
},
kids: []
}
];
In controller I have ajax function:
public function ajax(){
$parent = FirstLine::
select('yehida','data_type')
->where('first_year',2019)->where('second_year',2019)->where('first_period_no',1)->where('second_period_no',2)->where('periodical','רבעוני')
->addSelect(DB::raw('SUM(first_period) as first_period'))
->groupBy('yehida')
->groupBy('data_type')
->orderBy('yehida')
->orderBy('data_type')
->get();
$child = FirstLine::
select('yehida','hativa','data_type')
->where('first_year',2019)->where('second_year',2019)->where('first_period_no',1)->where('second_period_no',2)->where('periodical','רבעוני')
->addSelect(DB::raw('SUM(first_period) as first_period'))
->groupBy('yehida')
->groupBy('hativa')
->groupBy('data_type')
->orderBy('yehida')
->orderBy('hativa')
->orderBy('data_type')
->get();
$value = [];
foreach ($parent as $ch) {
$options = [];
foreach($child as $ch2) {
$options[] = ['data' => [
'yehida' => $ch2->yehida,
'hativa' => $ch2->hativa,
'data_type' => $ch2->data_type,
'first_period' => $ch2->first_period],
'kids' => []
];
if($ch->yehida == $ch2->yehida){
$value[] = [
'data' =>[
'yehida' => $ch->yehida,
'data_type' => $ch->data_type,
'first_period' => $ch->first_period
],
'kids' =>
$options,
];
}
}
}
$value = json_encode($value);
return response()->json($value);
}
My script with ajax call:
<script>
var temp;
$.ajax({
'async': false,
type: 'GET', //THIS NEEDS TO BE GET
url: '{!! route('get.ajax') !!}',
dataType: 'json',
success: function (data) {
temp = data;
},error:function(){
console.log(data);
}
});
var dataInJson = temp;
var settings = {
iDisplayLength: 20,
bLengthChange: false,
bFilter: false,
bSort: false,
bInfo: false
};
var tableT = new nestedTables.TableHierarchy(
'example',
dataInJson,
settings
);
tableT.initializeTableHierarchy();
var tableEle = document.querySelector('#example .table');
tableEle.addEventListener('onShowChildHierarchy', function(e) {
console.log(e);
});
// '#example' is wrapper ID for table hierarchy
var tableEle = document.querySelector('#example .table');
tableEle.addEventListener('onHideChildHierarchy', function(e) {
console.log(e);
});
</script>
How am I supposed to build my own JSON format so it will be like the JSON example? please help me

Unknown column 'getContent.movie_id' in 'field list

my whole schema
const Films = new GraphQLObjectType({
name: 'films',
interfaces: () => [MovieStream],
fields: () => ({
movie_id: {
type: GraphQLString,
},
id:{
type: GraphQLID
},
name: {
type: GraphQLString,
},
})
})
Films._typeConfig = {
sqlTable: "films",
uniqueKey: 'id',
}
const MovieStream = new GraphQLInterfaceType({
name: 'MovieStream',
fields: () => ({
id: {
type: GraphQLID,
},
movie_id: {
type: GraphQLString,
},
})
})
MovieStream._typeConfig = {
sqlTable: "movie_streams",
uniqueKey: 'id'
}
const QueryRoot = new GraphQLObjectType({
name: 'Query',
fields: () => ({
getContentList:{
type: new GraphQLList(Films),
args: {
id: {
type: GraphQLInt
},
permalink: {
type: GraphQLString
},
language: {
type: GraphQLString
},
content_types_id: {
type: GraphQLString
},
oauth_token:{
type: GraphQLString
}
},
resolve: (parent, args, context, resolveInfo) => {
return joinMonster.default(resolveInfo,{}, sql => {
return FilmDb.query(sql).then(function(result) {
return result[0];
});
} ,{dialect: 'mysql'});
},
}
})
})
module.exports = new GraphQLSchema({
query: QueryRoot
})
I have again modified my code still got the error
{
"errors": [
{
"message": "Unknown column 'getContent.movie_id' in 'field list'",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"getContentList"
]
}
],
"data": {
"getContentList": null
}
}
My previous post Is it possible to fetch data from multiple tables using GraphQLList
Please check and tell me where i am wrong??? I have already add the field still it does not access the field of that object type

Resources