Is there any way to fetch a collection by giving an initial model parameter to fetch().
To clear out: I have a model Human with attributes name (as a string) and numbers(array). I would like to find all the people in my database with given array of numbers. (Example: I have [123,342,4] in my array and for each number I would like to pull the people's name).
I've created a Human collection giving the model is human. And when I fetch like this it causes no problem;
humanCollection.fetch({
success:function(model,response){
console.log(model.toJSON().length);
var arr=model.toJSON();
for(var i=0;i<arr.length;i++)
console.log(arr[i].humanName+" ");
console.log("Success");
},
error:function(model,response){
console.log(response);
console.log("Failure");
}
});
I'm thinking of creating a dummy human object with no name and just numbers and later on passing the numbers to my php but .fetch() function doesn't seem to work when I put a parameter to the beginning. Not even the code below works;
humanCollection.fetch({},{
success:function(model,response){
console.log(model.toJSON().length);
var arr=model.toJSON();
for(var i=0;i<arr.length;i++)
console.log(arr[i].humanName+" ");
console.log("Success");
},
error:function(model,response){
console.log(response);
console.log("Failure");
}
});
What could be the problem? And is it logical for me to create a dummy human model in order to retrieve a collection of humans with the given numbers. That was the only way I could think of transferring the specific required json data.
I think you are messing up things.
As I understood the numbers are the Human.ids you want to fetch.
If this is correct these numbers have not any meaning to be part the the Human model. I rather will move them to the Collection.
You have to prepare the Collection to send a filter param in the URL of the fetch that informs to the server layer which Humans the Collection wants to fetch.
Also you have to prepare the server layer to be able to process the filter param with the ids of the Humans you want the server responses with.
So, in the Backbone Collection we can play with the data option of the fetch() method like this:
humanCollection.fetch({ data: { ids: [123, 342, 4] } });
The server will have to parse the ids param and return only the requested Humans.
Then in your Collection you will only have your selected Humans and you will can ask them for name or whatever.
Related
Quite new to GraphQL and lighthouse library, don't be too harsh.
Since I can't use any models because my data source is an API. I'm trying to create a custom resolver that will pass data to a service who will do everything necessary to retrieve data from the API.
And it constantly returns me this error: "Field \"address\" of type \"[Address!]\" must have a sub selection.",
I believe it's because of the fact I don't use models(just a wild guess)
So far my schema looks like this:
type Query {
address(address: String!): [Address!] #field(resolver: "Address#resolve")
}
type Address {
fullAddress: String!
lowestId: Int!
}
And the mentioned resolver:
public function resolve($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo): array
{
return array_map(
function ($address): array {
return [
'fullAddress' => $address->getFullAddress()
];
},
$this->service->getAddress($args['address'])
);
}
Thank you in advance!
The error is not even specific to Lighthouse, any GraphQL server will produce a similar error for what you are trying to do. I assume you are trying a query like this:
{
address(address: "foo")
}
Consider the graph in GraphQL: your server describes available data types and relations between them, forming a graph. Each type could have fields that lead to another type, and that type to another type, and so on. Those references can even form cycles. At some points, the graph may end: types such as scalar values mark the leaves of the graph.
Now, how does a server know which part of the graph you want to see and it should resolve? Through a query: a subselection of a part of that graph. That naturally limits how deep the server must go, it can do the minimal amount of work to return the parts of the graph you queried for.
One rule of queries is that you must always end up at leaf nodes. This is where the error message comes into play: the server sees that Address is not a leaf type and thus asks you to specify how deep you want to traverse the graph. A working query could be:
{
address(address: "foo") {
fullAddress
}
}
I've been looking into GraphQL as a replacement for some REST APIs of mine, and while I think I've wrapped my head around the basics and like most of what I see so far, there's one important feature that seems to be missing.
Let's say I've got a collection of items like this:
{
"id": "aaa",
"name": "Item 1",
...
}
An application needs a map of all those objects, indexed by ID as such:
{
"allItems": {
"aaa": {
"name": "Item 1",
...
},
"aab": {
"name": "Item 2",
...
}
}
}
Every API I've ever written has been able to give results back in a format like this, but I'm struggling to find a way to do it with GraphQL. I keep running across issue 101, but that deals more with unknown schemas. In my case, I know exactly what all the fields are; this is purely about output format. I know I could simply return all the items in an array and reformat it client-side, but that seems like overkill given that it's never been needed in the past, and would make GraphQL feel like a step backwards. I'm not sure if what I'm trying to do is impossible, or I'm just using all the wrong terminology. Should I keep digging, or is GraphQL just not suited to my needs? If this is possible, what might a query look like to retrieve data like this?
I'm currently working with graphql-php on the server, but I'm open to higher-level conceptual responses.
Unfortunately returning objects with arbitrary and dynamic keys like this is not really a first-class citizen in GraphQL. That is not to say you can't achieve the same thing, but in doing so you will lose many of the benefits of GraphQL.
If you are set on returning an object with id keys instead of returning a collection/list of objects containing the ids and then doing the transformation on the client then you can create a special GraphQLScalarType.
const GraphQLAnyObject = new GraphQLScalarType({
name: 'AnyObject',
description: 'Any JSON object. This type bypasses type checking.',
serialize: value => {
return value;
},
parseValue: value => {
return value;
},
parseLiteral: ast => {
if (ast.kind !== Kind.OBJECT) {
throw new GraphQLError("Query error: Can only parse object but got a: " + ast.kind, [ast]);
}
return ast.value;
}
});
The problem with this approach is that since it is a scalar type you cannot supply a selection set to query it. E.G. if you had a type
type MyType implements Node {
id: ID!
myKeyedCollection: AnyObject
}
Then you would only be able to query it like so
query {
getMyType(id: abc) {
myKeyedCollection # note there is no { ... }
}
}
As others have said, I wouldn't recommend this because you are losing a lot of the benefits of GraphQL but it goes to show that GraphQL can still do pretty much anything REST can.
Hope this helps!
I view my PHP code and JS code as one cohesive unit. I want to begin there interaction by creating an object on the client that looks like the structure below.
By doing this I only have to pass around one object. Sometimes all of the fields are populated, sometimes only 2 or more of the fields are populated.
So by trading off some wasted object properties, I only have to concern myself with passing o_p to different modules with in the MVC on the client and server.
I have functions to convert JavaScript to JSON to PHP.
Is this a valid approach?
Mo.o_p = function (type) {
return {
// current result or data about the data
result : 0,
// send client data
client : {
model : type,
page : {},
args : {}
},
// returned server data
server : {
bookmarks : {},
tweets : {},
smalls : {}
}
};
};
If your model requires these attributes and being empty is an important information for your application, i see no problem there. On the other hand, if your client and server objects are not necessarily connected and handled by different processes, there would be no need to couple them. Just passing some empty attributes should not be a performance problem.
I want to take an existing ExtJS 4 Grid and convert it into a JSON object for transport to the backend of my application (PHP). What do I need to do to make this happen? Do I simply need to overwrite the getState method of the grid and the getColumnState method of the column object?
What's the best approach for this?
Overriding the getColumnState for the column is a good idea. By default it assumes you'll be using the data with the same view again and that things like the column ids will be the same. I now have getColumnState returning an object that can be used as a config for a column. Add on whatever else you need from the grid and store as you find it useful.
I've found I need text, dataIndex, hidden, draggable, hideable, resizable, minWidth and flex. (And sometimes width).
Edit:
You want something like:
getColumnState: function () {
return {
text: this.text,
...
};
}
Look at the original getColumnState to see what they do about grouped columns and width vs flex if you need those things.
Then just call grid.headerCt.getColumnsState()
I have created a table in DB with name "member" having field "name", "college", "email", "zid" now I have created a class(in php) like
class member
{
private $name,$college,$email,$zid;
private function adduser
{
//function definition
}
public function autherise($id)
{
//function definition
}
}
now at index page I am taking these value as input from user using html form(validated by JS) now at action page of form I want to create object as obj=new member(); then calling the class function as obj->autherise($_post['zid']);
I want the defintion of autherise and adduser function like autherise check the uniqueness of zid and the calls adduser with remaining post variables and store them to object then add whole object in one query to DB.
I dont wan
insert into member(name,email,college,zid) values('$name,$email,$college,$zid')
I want to enter obj directly to the db
You can modify anything in functions
Thanks in Advance!!!
An "easy" solution to store a whole object somewhere, like in a database, is to serialize it – i.e. transform it to a string ; and, then, store that string in a single field in the database.
This can be done, in PHP, using the serialize function – and to de-serialize the string to an object, you'll use the unserialize function.
Another solution would be to serialize your object to the JSON format – nice thing with that is that JSON can be used directly from Javascript, and from lots of different programming languages, using the right libraries.
For JSON, see json_encode and json_decode
As a sidenote : note that if you store your data as serialized strings, it will be much harder to manipulate them in SQL : you will not be able to update them using a simple SQL query, for instance; and searching will be hard too.
This means you'll always have to fetch your data from the database, manipulate them with PHP, and send them back to the database – which might not always be such a good idea, depending on your needs.
I'm not sure what you're asking for. But maybe...just maybe you're looking for an object relational mapper (orm) , like e.g. doctrine.
If you were looking to store an object in a database you could serialize() or json_encode() the object into a String and then store it in a field in the table.
When you are ready to use it again you can unserialize() or json_decode() the String again.