Sharepoint 2010 Blog - Order rest query by Category - json

I've created a blog on Sharepoint 2010 and want to query the list via REST for reporting. I want to order the list by the default field Category (internal name PostCategory). Unfortunately, this is a multiselect field, therefore a simple "?$orderby=Category" doesn't work. I've also tried to expand the Category, but that doesn't work either.
Is there a chance, that I can order the list using rest? What about more then one selected Category? Can it be ordered by the first category, then the second, etc.?
If it's not possible using REST, what about ordering within JSON? I use a small javascript, that puts the list in a reporting format. Can I order within the JSON result?
Here is an example:
// Create REST-API URL
var strURL = "<REST-URL>";
// Get information from REST-API and create html output
$.getJSON(strURL, function(data) {
<Create output>
};
// Append to webpart
$('#<WebPartTitle>').append($(html));
EDIT: I've posted the question also here, since it's happening all in sharepoint

Category field (PostCategory internal name) is a multiple choice field, in SharePoint REST it is not supported to apply $orderby query option to this type of field.
But you could sort returned items using JavaScript.
The following example demonstrates how to order Posts by Category field.
There is one important note here:
Since Category field is a multiple choice field value, it is
assumed that only one category could be specified per post.
For that purpose FirstCategoryTitle property is introduced which
represent the title of first category in post item. This property is used > for sorting items
Example
var endpointUrl = 'http://contoso.intranet.com/blog/_vti_bin/listdata.svc/Posts?$expand=Category';
$.getJSON(endpointUrl, function(data) {
var items = data.d.results.map(function(item){
item.FirstCategoryTitle = (item.Category.results.length > 0 ? item.Category.results[0].Title : ''); //get first category
return item;
});
items.sort(postComparer); //sort by category
items.forEach(function(item){
console.log(item.Title);
});
});
function postComparer(x,y) {
return x.FirstCategoryTitle > y.FirstCategoryTitle;
}

Related

Updating Data within a unique randomly generated ID/KEY in firebase using HTML

function updateFirebase(){
const fb=firebase.database().ref()
//get field values
author = document.getElementById('uname').value
user_email = document.getElementById('umail').value
data = {author, user_email}
//update database
fb.child('Article/').update(data);
}
</script>
I have problem with my code. I want to update the data inside a table named "Article". Article has generated items with a unique key/id and each key has its own content. Lets say I want to be able to edit the "author" or change the "title", the problem is they each have a randomly generated key/id that I cant access. for example that "-LS39kReBHrKGqNj7h_". I can only save the data inside the "Article" tree but I cant change the "author" or the "title". How do i get a workaround this so I can change those properties?
Here is how my firebase looks like
It depends whether you have the record reference on the frontend before update or not (whether you have fetched it before you are trying to update it).
But generally, you have two options
You can store the key reference as an "id" field on the object.
To achieve that, you need two step process when creating the record at the first place
// Creates a new record in DB and returns it to you. Now you can get the "key"
const newRecord = firebase.database().ref('TABLE_NAME_REF').push();
newRecord.set({
id: newRecord.key
...
});
This is great if you fetch the list of records on the frontend and then you want to update one of them. Then you can just build the ref path like this
fb.child('Article/' + record.id ).update(data); // where record is the prefetched thing
You need to find the element based on its fields first. And once you have it, you can update it right away.
To achieve this, you can simply do something like:
firebase.database()
.ref('TABLE_NAME_REF') // let's say 'Article'
.orderByChild('RECORD_KEY') // Let's say 'author'
.equalTo('KEY_VALUE') // let's say 'zoranm'
.limitToFirst(1)
.once("value")
.then(res => {
// You need to loop, it always returns an array
res.forEach(record => {
console.log(record.key); // Here you get access to the "key"
fb.child('Article/' + record.key ).update(data); // This is your code pasted here
})
})

How to get ordered results from couchbase

I have in my bucket a document containing a list of ID (childList).
I would like to query over this list and keep the result ordered like in my JSON. My query is like (using java SDK) :
String query = new StringBuilder().append("SELECT B.name, META(B).id as id ")
.append("FROM" + bucket.name() + "A ")
.append("USE KEYS $id ")
.append("JOIN" + bucket.name() + "B ON KEYS ARRAY i FOR i IN A.childList end;").toString();
This query will return rows that I will transform into my domain object and create a list like this :
n1qlQueryResult.allRows().forEach(n1qlQueryRow -> (add to return list ) ...);
The problem is the output order is important.
Any ideas?
Thank you.
here is a rough idea of a solution without N1QL, provided you always start from a single A document:
List<JsonDocument> listOfBs = bucket
.async()
.get(idOfA)
.flatMap(doc -> Observable.from(doc.content().getArray("childList")))
.concatMapEager(id -> bucket.async().get(id))
.toList()
.toBlocking().first();
You might want another map before the toList to extract the name and id, or to perform your domain object transformation even maybe...
The steps are:
use the async API
get the A document
extract the list of children and stream these ids
asynchronously fetch each child document and stream them but keeping them in original order
collect all into a List<JsonDocument>
block until the list is ready and return that List.

Laravel - Group By & Key By together

Assuming I have the following MySQL tables to represent pricebooks, items and the relationship between them:
item - item_id|name|...etc
pricebook - pricebook_id|name|...etc
and the following pivot table
pricebook_item - pricebook_id|item_id|price|...etc
I have the correlating Eloquent models: Pricebook, Item and a repository named PricebookData to retrieve the necessary information.
Within the PricebookData repository, I need to get the pricebook data grouped by pricebook id and then keyed by item_id for easy access on client side.
If I do:
Pricebook::all()->groupBy('pricebook_id');
I get the information grouped by the pricebook_id but inside each pricebook the keys are simple numeric index (it arrives as js array) and not the actual product_id. So when returning to client side Javascript, the result arrives as the following:
pricebookData: {1: [{}, {}, {}...], 2: [{}, {}, {}...]}
The problem with the prices arriving as array, is that I can not access it easily without iterating the array. Ideally I would be able to receive it as:
pricebookData: {1: {1001:{}, 1002: {}, 1003: {}}, 2: {1001:{}, 1002: {}, 1003: {}}}
//where 1001, 1002, 1003 are actual item ids
//with this result format, I could simply do var price = pricebookData[1][1001]
I've also tried the following but without success:
Pricebook::all()->keyBy('item_id')->groupBy('pricebook_id');
The equivalent of what I am trying to avoid is:
$prices = Pricebook::all();
$priceData = [];
foreach ($prices as $price)
{
if (!isset($priceData[$price->pricebook_id]))
{
$priceData[$price->pricebook_id] = [];
}
$priceData[$price->pricebook_id][$price->item_id] = $price;
}
return $priceData;
I am trying to find a pure elegant Eloquent/Query Builder solution.
I think what you want is
Pricebook::all()
->groupBy('pricebook_id')
->map(function ($pb) { return $pb->keyBy('item_id'); });
You first group by Pricebook, then each Pricebook subset is keyed by item_id. You were on the right track with
Pricebook::all()->keyBy('item_id')->groupBy('pricebook_id');
unfortunately, as it is implemented, the groupBy resets previous keys.
Update:
Pricebook::all()->keyBy('item_id')->groupBy('pricebook_id', true);
(groupBy second parameter $preserveKeys)

Complicated Laravel relationship to generate view

I have Orders which contain any number of items stored in the items table (so a belongsToMany relationship between the two). The items are also categorized under itemtypes. When creating or editing an order I would like to load all items, categorized by itemtype, whether or not that order has any of the items. I was able to pull that up generically using the following:
$itemtypes = \App\Itemtype::with('items')
->orderBy('id','asc')
->get();
Then I loop through:
#foreach( $itemtypes as $itemtype )
{{$itemtype->name}}
#foreach( $itemtype->items as $item )
{{$item->name}}
#endforeach
#endforeach
This gives me something like:
NICU Items
- Baby Blanket
- Beaded Baby Cuddler
Miscellaneous Items
- Fitted Sheet
- Microfiber Towel
However, when I'm accessing a specific order which has records in item_order I want to display the saved quantities (stored in the pivot table). I know one way would be to add records for all items to item_order for every order created but that seems rather inefficient.
Item.php
public function orders() {
return $this->belongsToMany('App\Order', 'item_order', 'item_id', 'order_id') -> withPivot('id','quantity','createdby_user_id','weight','cost_billed', 'calc_by_weight', 'track_units');
}
Order.php
public function items() {
return $this -> belongsToMany('App\Item', 'item_order', 'order_id', 'item_id') -> withPivot('id','quantity','quantity_received','quantity_delivered','notes', 'createdby_user_id', 'weight', 'cost_billed', 'calc_by_weight', 'track_units');
}
UPDATE
I'm on the trail to a solution. I'm converting the collection to an array, loaded up with all items, modifying the array as needed, then using array_merge to replace the items that have quantities already in item_order.
This all works great - the only issue I'm having now is that when I load the order with it's items, items have an itemtype - a categorization and I'd like to group them by that. I'm not sure how to add a groupby to a relationship. If I figure it all out i'll post the full answer then.

MySQL: Merging different entities in one Query

I basically have three different classes of items that I want to show on a users wall: ratings, comments, and updates. This three are completey different entities, but because they all can appear on a users wall, I just call them "wallitem". The all have a timestamp property, which represents the date they were created.
I want to enable users to page through the wallitems, ordered by the timestamp. For example: last 10 wallitems. Or wallitems 20 to 30. Is there an MySQL Query that gives me the last 10 "wallitems", even though all different entities have different columns?
I could imagine, getting a list of items back, where each item has all the properties of all different entities, an additional property defining the type (for example "rating"), if it is in fact a rating, all other properties are just null. I would love to use such a dicationary in my php code:
foreach ($wallItemArray as $item) {
if ($item['type'] == "rating") {
$rating = $item; // use it as normal "rating"-entity
} else if ($item['type'] == "comment") {
$comment = $item; // use it as normal "comment"
}
// and so on for all different entities that could represent a wallitem in this context
}
Something like
SELECT 'rating' AS type, value AS r_val, NULL AS c_val
FROM Rating
UNION
SELECT 'comment' AS type, NULL AS r_val, comment_text AS c_val
FROM Comment
would get you started