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.
Related
I need to make a query where I can get "Place" table, but I have to exclude from that query all "Place" that are already part of the "LocationGroupPlace" table.
I have a class called Place and other called LocationGroupPlace
each LocationGroupPlace can contain many Places
these are the relations
in Place.php file
public function locationGroupPlace()
{
return $this->hasMany(LocationGroupPlace::class, 'place_id');
}
in LocationGroupPlace.php file
public function place(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Place::class);
}
I am trying to retrieve 5 items from "Place" that do not exist in "LocationGroupPlace", that is, the IDs of "Place" are not in the table of "LocationGroupPlace", for example these IDs
I'm trying to get the first 5 Place with all the table from LocationGroupPlace with a subquery (for test my subquery)
public function getUsedPlacesForGroups()
{
return Place::with(['locationGroupPlace' => function ($query){
$query->get();
}])->limit(5)->get();
}
but I can't get LocationGroupPlace, the relations section is empty
Note: locationGroupPlace is the function in Place
How can I get all LocationGroupPlace? my final idea is to exclude all "Places" included in "LocationGroupPlace"
If you want the places that doesn't exist in LocationGroupPlace then you can use doesntHave
$places= Place::doesntHave('locationGroupPlace')->limit(5)->get();
See Querying Relationship Absence
I am using DjangoFilterConnectionField in my project like this:
all_sessions = DjangoFilterConnectionField(SessionNode, filterset_class=AgendaFilter)
SessionNode is created based on Session model in my Django application. Now, I would like to be able to order these sessions by two fields: start_date and start_time.
To achieve that I've created the following filter:
class AgendaFilter(FilterSet):
class Meta:
model = Session
exclude = []
order_by = OrderingFilter(
fields=(
("start_date", "start_date"),
("start_time", "start_time")
)
)
When I filter sessions by only one field using orderBy , the query results are ordered correctly as expected. When I try to use both fields in the filter (shown below), the results returned are not ordered according to either of them:
{
allSessions(orderBy: "[start_date, start_time]") {
edges {
node {
id
startDate
startTime
}
}
}
}
I've tried different ways of passing the two fields to orderBy, but none of them worked for me. How can I correctly order by start_date and then by start_time in one query? According to the graphene documentation, this is possible:
Ordering
You can use OrderFilter to define how you want your returned results to be ordered.
Extend the tuple of fields if you want to order by more than one field.
Is this is a bug in graphene or am I doing something wrong?
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)
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;
}
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