Laravel Eloquent specific columns error - php

I have the following in Laravel 4.x using eloquent:
Book table has a dozen fields.
$single_data = Book::
selectRaw("GROUP_CONCAT(DISTINCT CAST(id as char) SEPARATOR ',') as type_id_list")
->first();
Question: the data returned is everything within the table inside Book AND type_id_list as seen from the selectRaw.
I would like to ONLY return what I specified within the selectRaw.
It was suggested that you get add an array of columns within first() or get() in order to retrieve this only - however it is not working with custom selectRaw where you specify an expression or your own wording. It throws an error and when the query is analyzed the array that you put in first/get gets appended as part of the select.
Does anyone have a work around?

first() will return only that particular column but wrapped in a Book object anyway, so use pluck() instead:
$single_data = Book::
selectRaw("GROUP_CONCAT(DISTINCT CAST(id as char) SEPARATOR ',') as type_id_list")
->pluck('type_id_list');

Related

Get specific columns using “with()” inside of another '

i need to get specific columns in the 2 methods that is being chained inside 'with', but it doesnt work, how can i select specific columns in each method inside of the 'with' method.
Event::with('eventBookmakers.bookmakerInfo')->find(2);
It's possible like this:
Event::with('eventBookmakers:column', 'eventBookmakers.bookmakerInfo:column')->find(2);
Remember to select the foreign key columns (e.g. event_id).
Try this, change column name to what column you want to retrieve.
Event::with('eventBookmakers.bookmakerInfo:columnName')->where('id', 2)->get();
or
Event::with('eventBookmakers.bookmakerInfo:columnName')->find(2);
Since you're selecting the two interrelated tables (relations) using dot . You may use select() and with() in a closure to add constraint and add the relations as well. So you'll end up with something like:
Event::with(['eventBookmakers' => function($bookmakers){
$bookmakers->select('id', 'event_id')->with(['bookmakerInfo' => function($info) {
$info->select('id', 'bookmaker_id');
}]);
}])->find(2);
Note the event_id passed to the first select ensure the relationship is loaded between Event and EventBookmaker(you can replace it with the relation_id you use instead) and same thing with using bookmaker_id so that it may load relation between Bookmaker and BookmakerInfo

Add custom field during select mysql in laravel query

I have this query in laravel 5.2
$obj_custom_stdy_data = QstCustomStudyData::where('student_id', $this->data_user['student_id'])
->select($list_id . ' as list_id ', 'chapter_id', 'subject_id', 'subject_code_id')
->get()
->toArray();
Well I have a fixed value $list_id got from top code. Actually I want to add new field during query selection as list_id. However I got error for such that method.
When I tried in mysql IDE for example:
SELECT (1+2) as total, c.* FROM users
Then the result is no wrong at all.
Is that anyway to write in query builder for laravel instead of raw style?
You can take the use of DB::raw() method of QueryBuilder like this:
->select(DB::raw('(1+2) as total'));
See more about Query Builder's Raw Expressions
Hope this helps!

Laravel groupBy Database query Builder not working

I have this problem in a query using laravel groupBy, it simply return a groupBy error. I have read the documentation about this but can't really figure it out. I also read the same problem pointing that it is because of postgreSQL that I need to include all the columns in grouBy clause. I tried it but still it doesn't return the distinct values. Please help me with this. Below is my code. Thanks a lot.
Controller function
public function index(){
$purchases = Purchase::groupBy('purchase_order_id')->get();
return view('purchases/purchases_crud', ['allPurchases' => $purchases]);
}
Table to query
Error
QueryException in Connection.php line 680:
SQLSTATE[42803]: Grouping error: 7 ERROR: column "purchases.id" must appear
in the GROUP BY clause or be used in an aggregate function
LINE 1: select * from "purchases" group by "purchase_order_id"
^ (SQL: select * from "purchases" group by "purchase_order_id")
There you have it add group by "purchases.id" or restrict the select to only the operates that are needed.
->select("purchase_order_id","purchases.id")
->groupBy("purchases.id") // add if possible
Agreggates for your case should mean something like ->select("sum(po_total)")
If we group by id, we get all results as id is unique, my mistake. You want something like this
DB::table("purchases")->select("purchase_order_id", DB:raw("sum(po_total)"))->groupBy("purchase_order_id")->g‌​et();
Rule of thumb is you either select a field with Sum() or have it on the group by

Need a INT from Eloquent. Getting JSON string

I have this query:
static function findIdOnName($pageName){
return Fanpages::select('id')
->where('url', '=', $pageName)
->get();
}
Response: (when done print_r)
[{"id":17}]
I just want the INT (in this case 17) I searched the interwebs for it, but I can't find anthing about it. Randomly tried adding ->toString() etc to the query, but so far, no good.
Your code returns a Collection with a single Model (or multiple models if there are more matching the where clause), while the method you need is pluck:
return Fanpages::where('url', '=', $pageName)->pluck('id');
// returns INT 17
as it returns value for column id of the first row matching WHERE clause.
If you do not return a view with data, then Laravel will automatically convert your data into json. In order to accomplish what you want you can simply do something like
$data = Fanpages::select('id')->where('url', '=', $pageName)->get();
die($data->id);
However, exiting the application like this isn't recommended. You should either keep the json response and work with that, or send the data to a basic blade template.

Doctrine orderBy on SUM() field with alias

I am trying to do a simple query in doctrine but struggling.
$query->select(array(
'app_title' => 'u.title',
'user_name' => 'u.user_name',
'first_used' => 'MIN(u.creation_time)',
'last_used' => 'MAX(u.stop_time)',
'total_usage' => 'SUM(u.stream_seconds)',
))
->from(self::USAGE_TABLE, 'u')
->orderBy('total_usage', 'DESC');
Obviously I get an error about the column name not being known because Doctrine is using it's own aliases (sclr4).
However, if I try and order by the actual value; SUM(u.stream_seconds), then I get an unexpected bracket in the order by clause, I'm pretty sure SQL doesnt support this.
So, I am simply trying to put data in a table and handle the sorting of the columns. This seems so simple, how do I do it? Any ideas?
You can orderBy the SUM result field by list it in query projection by aliasing result using AS.
If you want to use an aggregate function such as MIN(), MAX(), AVG(), you have to use GROUP BY.
Try simmilar to this, which works perfectly for me (BTW instead of associative array in select method):
$q = $this->em()->createQueryBuilder();
$q->select(['product.id', 'product.title'])
->addSelect('SUM(product.price) AS HIDDEN stat_sum_realised')
->from('ModuleAdmin\Entity\ProductEntity', 'product')
->groupBy('product.id');
$q->orderBy('stat_sum_realised', 'DESC');
Aggregate functions are detailed here (for e.x. for MySQL):
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html
As of Doctrine ORM 2.3, you can also use the HIDDEN keyword, which will avoid (in this case) stat_sum_realised from getting hydrated into your resultset.

Categories