Can the with function be used with a GroupBy clause in Laravel Eloquent? - group-by

Can the with function be used with a GroupBy clause in Laravel Eloquent? Does it serve any purpose if I have specific items to select using the Select Clause?
Following is the query that I currently have
Order::with('Campaign')
->where('isapproved','=','Y')
->groupBy('campaign_id')
->orderBy(DB::raw('COUNT(id)','desc'))
->get(array(DB::raw('COUNT(id) as totalsales')));
The order table has a column name campaign_id which belongsTo the table named campaigns. I would like to get the total count of the sales from the order table against each campaign and need to show in the following manner.
Total Sales Campaign
-------------------------
200 Campaign1
500 Campaign2
300 Campaign3
Should I have to perform a specific select or can I access the values of the Campaign table from the above query?

If the referenced column required by the Model specified on the With function is retrieved in the SELECT clause, then the With function is taken into consideration by the above query. The rectified query will be
$groupedSalesCampaign = Order::with('Campaign')
->where('isapproved','=','Y')
->groupBy('campaign_id')
->orderBy(DB::raw('COUNT(id)','desc'))
->get(array(DB::raw('COUNT(id) as totalsales'),'campaign_id'));
This way the Campaign information can be retrieved using
foreach($groupedSalesCampaign as $campaign)
{
Log::info($campaign->foo->bar);
}
Edited.

Related

Sails 1.0 Group By

Now that groupBy is deprecated, how can I mimic a SQL command like SELECT COUNT(*) FROM table GROUP BY xxx using the Waterline ORM ?
This page recommends using .sum() and .avg() but these methods are for number-type columns. Here I want to be able to count the rows of grouped columns, whatever type it is.
I think for specific groupBy query, you've got two choices.
The first one is a 2 step action.
1) Select all the unique element "group by field" you've got in the database.
2) Then count the record for each unique group by field element.
The second one is to use .sendNativeQuery() wich allow you to send a native SQL query to the datastore (you can use this only if you use a real SQL server and not the embedded Sails.JS database)
sendNativeQuery() Documentation

How to get the particular row by column in smartsheet api

I am using smartsheet as a database and I want to query the smartsheet by column name equals value like in sql db for example: To get the particular row of Employee sheet where salary equal to 10000. But documentation describes only how to get list of rows and how to update and delete rows by row id.
https://smartsheet-platform.github.io/api-docs/?java
What i want is to achieve without knowing id of the row. But I can do by search function by searching the salary of the employee
https://api.smartsheet.com/2.0/search?query=10000
and the response of above call will have row id and again i should make a call with rowid to get that row by below call which I don't want.
GET /sheets/{sheetId}/rows/{rowId}
Can anyone help me out?
Although some folks do try to use Smartsheet like a database, it's not really designed to be queried via API in the same way that you'd use transact SQL to query a SQL database.
I don't believe the scenario that you've described (i.e., using the Smartsheet API to retrieve row(s) in a sheet where [column value] = [specified value]) is possible. Instead, you'll have to use the API to get the data in the sheet (Get Sheet) and then in your code, query the data that you received in the API response (to identify the row(s) that match your query criteria).

Number each nested table inside a master table on a Jasper report

So i have the following issue. In my database I have a table named
bp_minutes_app.
This table stores records of minutes from committee meetings. Each minute can consist of many files. The database design regarding minutes is the following:
The table bp_minutes_attachments is connected via a foreign key to the bp_minutes_app and holds the following information:
description, createdby
The table
bp_files
is connected via a foreign key to the
bp_minutes_app
and holds the file along other information. We are interested in taking only the name and id of the file (the latter in order to create a hyperlink to the file, but this is out of scope of the present question).
Final remark. All those tables are linked to the master
bp_full
table that is joined only to get the id of each specific report.
In my report I want to print on a table all minutes and the accompanying information (file name, description, createdby, submission date), but make a separate entry for each minute. In order to achieve this, I first created a table that uses the following dataset:
SELECT bp_minutes_app.id
FROM bp_minutes_app
INNER JOIN bp_full ON
bp_minutes_app.bp_full_app_id = bp_full.id
WHERE bp_full.id = $P{id}
With this dataset I retrieve each minutes record. In my example, I get two records with ids 39 and 40.
Inside this table I nested another table to retrieve information for each file in each minutes record. The dataset that I used is the following:
SELECT bp_minutes_app.submission_date,
bp_minutes_attachments.createdby,
bp_minutes_attachments.description,
bp_files.id,
bp_files.name
FROM bp_minutes_attachments
left JOIN bp_minutes_app ON
bp_minutes_attachments.bp_minutes_app_id = bp_minutes_app.id
AND bp_minutes_app.id = $P{mid}
left JOIN bp_full ON
bp_minutes_app.bp_full_app_id = bp_full.id
left JOIN bp_files ON
bp_minutes_attachments.bp_file_id = bp_files.id
WHERE
bp_full.id = $P{id}
The id parameter is used again to take the specific report and the mid parameter to take a specific minute. On parameter specification mid is declared as follows:
mid = $F{id}
, where id is the bp_minutes_app.id.
Following this setup I managed to get nested tables for each minute (forgive me for the greek headers):
What I want to do is number each subtable from 1...n, according to the number of minutes/ subtables. How can I achieve this? I tried to create a suitable variable but it was not met with success. I want to somehow "save" in a parameter / variable the count of bp_minutes_app records and manipulate this number for each nested table header, instead of just numbering each table with the corresponding id.
Sorry for the long post but I am new to Jasper and I wanted to be clear about the steps I have taken and what I want to achieve.
Alot of sql not much jrxml in your post so I start by guessing.
Have you tried something like this in the jrxml:
<variable name="counter" class="java.lang.Integer" calculation="Count">
<variableExpression><![CDATA[$F{id}]]></variableExpression>
</variable>

Filter and display database audit / changelog (activity stream)

I'm developing an application with SQLAlchemy and PostgreSQL. Users of the system modify data in 8 or so tables. Consider this contrived example schema:
I want to add visible logging to the system to record what has changed, but not necessarily how it has changed. For example: "User A modified product Foo", "User A added user B" or "User C purchased product Bar". So basically I want to store:
Who made the change
A message describing the change
Enough information to reference the object that changed, e.g. the product_id and customer_id when an order is placed, so the user can click through to that entity
I want to show each user a list of recent and relevant changes when they log in to the application (a bit like the main timeline in Facebook etc). And I want to store subscriptions, so that users can subscribe to changes, e.g. "tell me when product X is modified", or "tell me when any products in store S are modified".
I have seen the audit trigger recipe, but I'm not sure it's what I want. That audit trigger might do a good job of recording changes, but how can I quickly filter it to show recent, relevant changes to the user? Options that I'm considering:
Have one column per ID type in the log and subscription tables, with an index on each column
Use full text search, combining the ID types as a tsvector
Use an hstore or json column for the IDs, and index the contents somehow
Store references as URIs (strings) without an index, and walk over the logs in reverse date order, using application logic to filter by URI
Any insights appreciated :)
Edit It seems what I'm talking about it an activity stream. The suggestion in this answer to filter by time first is sounding pretty good.
Since the objects all use uuid for the id field, I think I'll create the activity table like this:
Have a generic reference to the target object, with a uuid column with no foreign key, and an enum column specifying the type of object it refers to.
Have an array column that stores generic uuids (maybe as text[]) of the target object and its parents (e.g. parent categories, store and organisation), and search the array for marching subscriptions. That way a subscription for a parent category can match a child in one step (denormalised).
Put a btree index on the date column, and (maybe) a GIN index on the array UUID column.
I'll probably filter by time first to reduce the amount of searching required. Later, if needed, I'll look at using GIN to index the array column (this partially answers my question "Is there a trick for indexing an hstore in a flexible way?")
Update this is working well. The SQL to fetch a timeline looks something like this:
SELECT *
FROM (
SELECT DISTINCT ON (activity.created, activity.id)
*
FROM activity
LEFT OUTER JOIN unnest(activity.object_ref) WITH ORDINALITY AS act_ref
ON true
LEFT OUTER JOIN subscription
ON subscription.object_id = act_ref.act_ref
WHERE activity.created BETWEEN :lower_date AND :upper_date
AND subscription.user_id = :user_id
ORDER BY activity.created DESC,
activity.id,
act_ref.ordinality DESC
) AS sub
WHERE sub.subscribed = true;
Joining with unnest(...) WITH ORDINALITY, ordering by ordinality, and selecting distinct on the activity ID filters out activities that have been unsubscribed from at a deeper level. If you don't need to do that, then you could avoid the unnest and just use the array containment #> operator, and no subquery:
SELECT *
FROM activity
JOIN subscription ON activity.object_ref #> subscription.object_id
WHERE subscription.user_id = :user_id
AND activity.created BETWEEN :lower_date AND :upper_date
ORDER BY activity.created DESC;
You could also join with the other object tables to get the object titles - but instead, I decided to add a title column to the activity table. This is denormalised, but it doesn't require a complex join with many tables, and it tolerates objects being deleted (which might be the action that triggered the activity logging).

SQL: Multiplying two columns(from different tables) and Inserting/Updating(one of the tables)

I have two tables:
Stock:
ItemID Quantity
111 5.0
222 3.0
Item:
ItemID Sellper
111 1.0
222 2.0
I want to use the ItemID to perform Quantity*Sellper and the use the result to update the Quantity field in Stock Table.
SELECT *,Stock.StockQuantity * Item.SellPer As FinaLStockQuantity
FROM Stock, Item
WHERE Stock.ItemID = Item.ItemID
I can get the results of the product of two columns using the above query but can not get it to update the stock table.
Can someone please help?
P.S: Apologies for the horrible formatting of this post
You need the UPDATE statement to modify existing data. The documentation has numerous examples on how to update one table from data that comes from other tables.
In your case, assuming there is only one Item row per Stock row, you can write the following query
UPDATE Stock
SET Quantity=Quantity*Item.SellPer
From Stock s inner join Item i
on s.ItemID=i.ItemID