Partial selection on Inner Join - javascript

I need select ony on field to services, look:
async find(): Promise<AccountEntity[]> {
const result = await this.repository
.createQueryBuilder("account")
.select(['account', 'accountServices', 'service.description'])
.leftJoinAndSelect("account.accountAndServices", "accountServices")
.leftJoinAndSelect("accountServices.service", "service")
.getMany();
return result === undefined ? null : result;
}
How to ? please.
I don't want null attributes to appear and I also want to choose which attributes to show
I need :
{
"message": "",
"success": true,
"data": [
{
"id": 1,
"name": "STONES TECNOLOGIA LTDA",
"accountAndServices": [
{
"service": {
"name": "Construção de uma casa",
},
"date_initial": "2021-08-01T07:39:18.000Z",
"date_final": "2021-08-01T07:39:20.000Z",
"value": "10.00",
"created_by": 1,
"is_active": true,
"id": 1,
"pay_day": 10,
"nfse": 0,
"created_at": "2021-08-01T07:39:27.000Z",
},
{
"service": {
"name": "Desenvolvimento de sistemas",
},
"date_initial": "2021-08-01T07:40:01.000Z",
"date_final": "2021-08-01T07:40:02.000Z",
"value": "20.00",
"created_by": 1,
"is_active": true,
"id": 2,
"pay_day": 20,
"nfse": 0,
"created_at": "2021-08-01T07:40:11.000Z",
}
]
}
],
"errors": null
}
I Need selection only field on entity join.

Select with innerJoin you must use addSelect(...).
The find function must not manipulate any data and should return an array of AccountEntity (empty if not found):
function find(): Promise<AccountEntity[]> {
return this.repository
.createQueryBuilder("a")
.innerJoin("account.accountAndServices", "as")
.innerJoin("accountServices.service", "s")
.select(['a.id', 'a.name', 'a.status'])
.addSelect(['as.date_initial', 'as.date_final', 'as.service_id', 'as.value', 'as.nfse', 'as.value', 'as.created_by', 'is_active', 'pay_day', 'created_at'])
.addSelect(['s.name'])
.getMany();
}
Note that to obtain the result from the function you must use await.
Moreover, surround it with try and catch for a better error handling.
Example:
try {
const accounts: AccountEntity[] = await find();
} catch(error) {
console.error(`Error: ${error}`);
}
To transform the array of AccountEntity to another object:
function transform(accounts?: AccountEntity[]) {
return {
message: "",
success: accounts !== undefined,
data: accounts,
errors: null
};
}

Related

Laravel Sorted Collection Gets Undone When Passed to Javascript [duplicate]

Here is my code :
public function list()
{
$users = User::with('group')->get()->toArray();
return response()->json([
'clients' => array_filter($users, function ($r) {
return $r['group']['name'] === 'client';
}),
'employes' => array(array_filter($users, function ($r) {
return $r['group']['name'] !== 'client';
})),
]);
}
Here is the response :
{
"clients": {
"2": {
"id": 3,
"name": "Client 1",
"email": "client#a.fr",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 4,
"group": {
"id": 4,
"name": "client"
}
},
"3": {
"id": 4,
"name": "Client 2",
"email": "client2#a.fr",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 4,
"group": {
"id": 4,
"name": "client"
}
},
"4": {
"id": 5,
"name": "Client 3",
"email": "client3#a.fr",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 4,
"group": {
"id": 4,
"name": "client"
}
}
},
"employes": [
[
{
"id": 1,
"name": "Alexis",
"email": "alexis#a.fr",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 1,
"group": {
"id": 1,
"name": "admin"
}
},
{
"id": 2,
"name": "guest",
"email": "guest#a.fr",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 2,
"group": {
"id": 2,
"name": "guest"
}
}
]
]
}
I tried to change the conditions of the array_filter. Sometimes I have an array, sometimes I have an object. I don't understand how this is determined
Stackoverflow tells me "It looks like your post is mostly code; please add some more details." So ... what details to add?
Thank you
Internally array_filter() filters matching entries from the array, and returns them with their indices intact. This is very important, as it is the core reason you're getting an object and not an array in JavaScript.
In PHP, this is fine; arrays can start at 0, or another index, such as 2, and function as an array without issue. This is due to the existence of indexed (0-based) and associative (numeric/non-numeric key based) arrays.
In JavaScript, arrays cannot be "associative", i.e. they must start at 0. object classes on the other hand function similarly to associative arrays, but the key difference is that they aren't explicitly arrays.
Now that you know the why, the next question is "how do I fix this?" The simple method is to wrap array_filter() with a function that simply returns the values of the new array. This inherently will "re-index" the array with 0-based values, which when converted to JSON will result in correct arrays being returned:
$users = User::with('group')->get()->toArray();
$clients = array_filter($users, function($r){
return $r['group']['name'] === 'client';
});
$groups = array_filter($users, function ($r) {
return $r['group']['name'] !== 'client';
});
return response()->json([
'clients' => array_values($clients),
'groups' => array_values($groups)
]);
As a sidenote, Collection classes have similar logic, and I prefer to use Laravel's Collection class whenever possible:
$users = User::with('group')->get();
$clients = $users->filter(function($r){
$r->group->name === 'client';
});
$groups = $users->filter(function($r){
$r->group->name !== 'client';
});
return response()->json([
'clients' => $clients->values(),
'groups' => $groups->values()
]);
But again, that's my preference; either approach should work, so use what you're used to.
References:
PHP Array Methods:
https://www.php.net/manual/en/function.array-filter.php
https://www.php.net/manual/en/function.array-values.php
Laravel Collection Methods:
https://laravel.com/docs/5.8/collections#method-filter
https://laravel.com/docs/5.8/collections#method-values
This works for me. I hope this will help anyone.
return response(['STATUS'=>'true','message'=>'Your Message','response'=>
array_values('clients' => array_filter($users, function ($r) {
return $r['group']['name'] === 'client';
})),
'employes' => array_values(array_filter($users, function ($r) {
return $r['group']['name'] !== 'client';
}))
)]);
If in response array you will get a result like an index key and you want the response in object array [{ ... }] then use array_values() will resolve your problem.
"clients": {
"2": {
"id": 3,
"name": "Client 1",
"email": "client#a.fr",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 4,
"group": {
"id": 4,
"name": "client"
}
},
simply add ->values() it will reorder array keys
users = User::with('group')->values();

Javascript For Each Object inside Array containing a property that is Array check If Value Matches

For each object inside this array containing userHandle array loop through that array(userHandle one) and check if one of those values matches some string I choose called uid. How to write that code in Javascript?
Array [
Object {
"avatar": null,
"hugCount": 2,
"id": 35,
"liked": false,
"name": "fhfdhdhf",
"text": "Yoho",
"timestamp": 1610471860157,
"uid": "FOgepuJqxXfkHxI8OAV2KMWodXo1",
},
Object {
"avatar": null,
"hugCount": 1,
"id": 34,
"liked": true,
"mood": 2,
"name": "fhfdhdhf",
"text": "I'm fine today.",
"timestamp": 1607943705709,
"uid": "FOgepuJqxXfkHxI8OAV2KMWodXo1",
"userHandle": Array [
"Aw8AUj1mPkON1Fd1s6LhkNETHfb2",
"LrIwIx9I1xQBJ7aeCSrinpEaDP53",
],
}]
Try this code:
var uid = "LrIwIx9I1xQBJ7aeCSrinpEaDP53";
yourArray.forEach(function(item, _){
return item['userHandle']?.indexOf(uid);
});
The '?' is to make sure your Object contains the 'userHandle' property
This is the function you need... and below you can see how to use it.
You need to pass the value you are looking for, and the array with the information.
function findInUserHandle(uidValue, array)
{
return array.reduce
(
(acum, current) =>
current.userHandle && current.userHandle.indexOf(uidValue) !== -1 || acum,
false
)
}
let array = [
{
"avatar": null,
"hugCount": 2,
"id": 35,
"liked": false,
"name": "fhfdhdhf",
"text": "Yoho",
"timestamp": 1610471860157,
"uid": "FOgepuJqxXfkHxI8OAV2KMWodXo1",
},
{
"avatar": null,
"hugCount": 1,
"id": 34,
"liked": true,
"mood": 2,
"name": "fhfdhdhf",
"text": "I'm fine today.",
"timestamp": 1607943705709,
"uid": "FOgepuJqxXfkHxI8OAV2KMWodXo1",
"userHandle":[
"Aw8AUj1mPkON1Fd1s6LhkNETHfb2",
"LrIwIx9I1xQBJ7aeCSrinpEaDP53",
],
}
]
findInUserHandle('something', array) //? false
findInUserHandle('Aw8AUj1mPkON1Fd1s6LhkNETHfb2', array) //? true
findInUserHandle('mood', array) //? false

Laravel - why json response return sometimes an array sometimes an object

Here is my code :
public function list()
{
$users = User::with('group')->get()->toArray();
return response()->json([
'clients' => array_filter($users, function ($r) {
return $r['group']['name'] === 'client';
}),
'employes' => array(array_filter($users, function ($r) {
return $r['group']['name'] !== 'client';
})),
]);
}
Here is the response :
{
"clients": {
"2": {
"id": 3,
"name": "Client 1",
"email": "client#a.fr",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 4,
"group": {
"id": 4,
"name": "client"
}
},
"3": {
"id": 4,
"name": "Client 2",
"email": "client2#a.fr",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 4,
"group": {
"id": 4,
"name": "client"
}
},
"4": {
"id": 5,
"name": "Client 3",
"email": "client3#a.fr",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 4,
"group": {
"id": 4,
"name": "client"
}
}
},
"employes": [
[
{
"id": 1,
"name": "Alexis",
"email": "alexis#a.fr",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 1,
"group": {
"id": 1,
"name": "admin"
}
},
{
"id": 2,
"name": "guest",
"email": "guest#a.fr",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 2,
"group": {
"id": 2,
"name": "guest"
}
}
]
]
}
I tried to change the conditions of the array_filter. Sometimes I have an array, sometimes I have an object. I don't understand how this is determined
Stackoverflow tells me "It looks like your post is mostly code; please add some more details." So ... what details to add?
Thank you
Internally array_filter() filters matching entries from the array, and returns them with their indices intact. This is very important, as it is the core reason you're getting an object and not an array in JavaScript.
In PHP, this is fine; arrays can start at 0, or another index, such as 2, and function as an array without issue. This is due to the existence of indexed (0-based) and associative (numeric/non-numeric key based) arrays.
In JavaScript, arrays cannot be "associative", i.e. they must start at 0. object classes on the other hand function similarly to associative arrays, but the key difference is that they aren't explicitly arrays.
Now that you know the why, the next question is "how do I fix this?" The simple method is to wrap array_filter() with a function that simply returns the values of the new array. This inherently will "re-index" the array with 0-based values, which when converted to JSON will result in correct arrays being returned:
$users = User::with('group')->get()->toArray();
$clients = array_filter($users, function($r){
return $r['group']['name'] === 'client';
});
$groups = array_filter($users, function ($r) {
return $r['group']['name'] !== 'client';
});
return response()->json([
'clients' => array_values($clients),
'groups' => array_values($groups)
]);
As a sidenote, Collection classes have similar logic, and I prefer to use Laravel's Collection class whenever possible:
$users = User::with('group')->get();
$clients = $users->filter(function($r){
$r->group->name === 'client';
});
$groups = $users->filter(function($r){
$r->group->name !== 'client';
});
return response()->json([
'clients' => $clients->values(),
'groups' => $groups->values()
]);
But again, that's my preference; either approach should work, so use what you're used to.
References:
PHP Array Methods:
https://www.php.net/manual/en/function.array-filter.php
https://www.php.net/manual/en/function.array-values.php
Laravel Collection Methods:
https://laravel.com/docs/5.8/collections#method-filter
https://laravel.com/docs/5.8/collections#method-values
This works for me. I hope this will help anyone.
return response(['STATUS'=>'true','message'=>'Your Message','response'=>
array_values('clients' => array_filter($users, function ($r) {
return $r['group']['name'] === 'client';
})),
'employes' => array_values(array_filter($users, function ($r) {
return $r['group']['name'] !== 'client';
}))
)]);
If in response array you will get a result like an index key and you want the response in object array [{ ... }] then use array_values() will resolve your problem.
"clients": {
"2": {
"id": 3,
"name": "Client 1",
"email": "client#a.fr",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 4,
"group": {
"id": 4,
"name": "client"
}
},
simply add ->values() it will reorder array keys
users = User::with('group')->values();

How do you render objects from json

I need to render some images from some json that I am being given. The code looks like
class App extends React.Component {
componentDidMount() {
$.get(
"url"
data => {
});
}
render() {
return React.createElement("div", null, "hello");
}}
ReactDOM.render(React.createElement(App, null), document.body);
"url" is the json that I have passed in (but I do not want to make it public). It looks similar to this:
{
"total_count": null,
"_links": {
"self": {
"href": ""
},
"next": {
"href": ""
}
},
"_embedded": {
"showorks": [{
"id": "",
"slug": "",
"created_at": "",
"updated_at": "",
"title": "",
"category": "",
"medium": ",
"date": "",
"dimensions": {
"in": {
"text": "",
"height": 70.9,
"width": 70.9,
"depth": null,
"diameter": null
},
"cm": {
"text": "180.1 × 180.1 cm",
"height": 180.1,
"width": 180.1,
"depth": null,
"diameter": null
}
},
"published": true,
"website": "",
"signature": "",
"series": null,
"prov": "",
"lit": "",
"hist": "",
"isst": "",
"additional_information": "",
"image_rights": "",
"blurb": "",
"unique": false,
"maker": null,
"icon": ,
"inquire": false,
"acquire": false,
"share": true,
"message": null,
"sell":,
"image_versions": ,
"_links": {
"thumbnail": {
"href": ""
},
"image": {
"href": "",
"templated": true
},
"partner": {
"href": ""
},
"self": {
"href": ""
},
"link": {
"href": ""
},
"genes": {
"href": ""
},
"rar": {
"href": ""
},
"cim": {
"href": ""
},
"coll": {
"href": ""
}
},
"_embedded": {
"editions": []
}
}, {
"id": "",
I need the thumbnail for each id but I'm not sure how to iterate through the json to pull out each thumbnail in react/javascript
First, I totally recommend you to use JSX syntax to use React better. To do that, you will need a few Javascript Array helper function and some methods.
As you can see below:
class App extends React.Component
{
componentDidMount()
{
// We could imagine the incoming JSON data
// const exampleJson =
// {
// elements:
// [
// { href: 'example1', text: 'link value', style: { height: '10px' } },
// ],
// };
// This fetch API will help you to get JSON from URL like JQuery $.get
const exampleJson = fetch('http://example.com/links.json')
.then(function(response)
{
return response.json(); // get the values of JSON as string type
})
.then(function(myJson)
{
return JSON.stringify(myJson); // convert the JSON data to javascript object
});
this.setState(exampleJson); // it's like this.setState({ elements: [array values] });
console.log(exampleJson); // to do debug of your JSON data
}
render()
{
// we getting the elements array from state object
// with object spread operator
const { elements } = this.state;
// get values all of your json array
// loop values to do React element
// return all new values to use loopAndSaveElements variable
const loopAndSaveElements = elements
.map(({ text, ...otherProps}) => React.createElement('a', otherItems, text));
// send return div of React as loopAndSaveElements as array children
return React.createElement("div", null, loopAndSaveElements);
}
}
By the way, i didn't run the snippet of example. But i hope it give you an information.
ES6+ Sources:
const
Array map
spread syntax
JSX syntax
fetch API

Check all the lines

I am a bit stuck, I need a way to make sure all the lines contain "new" in the status or otherwise return false,
var found = data.Lines.find(function(line) {
if (line.status.some(({
status
}) => status !== "new")) {
return false;
}
});
See example http://jsfiddle.net/sucL9rnm/10/
Data
var data = {
"id": 1,
"Lines": [{
"id": 111,
"status": [{
"status": "new"
}]
},
{
"id": 111,
"status": [{
"status": "new"
}]
},
{
"id": 111,
"status": [{
"status": "new"
}]
}
]
}
I gotchu man. Here's a simple solution with a for-loop:
function isFound() {
for (var i = 0; i < data.Lines.length; i++)
if (data.Lines[i].status[0].status !== 'new')
return false;
return true;
}
JSFiddle: http://jsfiddle.net/sucL9rnm/24
This function will return true only if all nested elements of data.lines have the "new" status attribute. Give it a try. Let me know if you have any additional questions.
Here is a possible solution :
var data = {
"id": 1,
"Lines": [{
"id": 111,
"status": [{
"status": "new"
}]
},
{
"id": 111,
"status": [{
"status": "new"
}]
},
{
"id": 111,
"status": [{
"status": "new"
}]
}
]
}
console.log(data.Lines.every(d => d.status[0].status === 'new'));
Using .map and .filter:
data.Lines.filter(line => {
return line.status && line.status.map(item => item.status)
.filter(status => status == 'new')
.length == 0
})
.length > 0
This solution takes into account that data.Lines may have a status with more than one object in it.
Just an approach using short IF and filter
(data.Lines.filter(o=>{
return o.status[0].status !='new';
}).length)?console.log(false):console.log(true)
With status length more than 0:
(data.Lines.filter(o=>{
return o.status.filter(o2=>{
return o2.status !='new';
}).length
}).length)?console.log(false):console.log(true)
Here a non-standard approach, the advantage, is not necessary to know exactly how the object is.
(data.Lines.length == JSON.stringify(data).match(/new/g).length)?console.log(true):console.log(false);

Categories