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!
Related
Here my MySQL query (work in phpMyAdmin) :
SELECT workcenter, (SUM(w1+w2 +w3 +w4)/ (COUNT(DISTINCT(teknisi))*40*4) )*100 AS total FROM `team` GROUP by workcenter ORDER BY total
then, i try in Laravel Sintax like this below (not work) :
$sql = Team::groupBy('workcenter')->select('workcenter', \DB::raw('(SUM(w1+w2+w3+w4)/ (COUNT(DISTINCT(teknisi))*30*4) )*100 AS total'))
->OrderBy('total', 'Desc')
->get();
When i run the laravel sintax, its doesn't show any errors, but the output is nothing..
Please anyone help me to convert the MySQL query to Laravel Sintax. Thank you!
I think you are close enough, however, this doesn't look like a correct way to group by with Eloquent ORM. Try using raw expressions, something like this might work:
$sql = DB::table('team')
->select(DB::raw('workcenter, (SUM(w1+w2 +w3 +w4)/ (COUNT(DISTINCT(teknisi))*40*4) )*100 as total'))
->orderBy('total', 'desc')
->groupBy('workcenter')
->get();
More about raw expressions here - https://laravel.com/docs/6.x/queries#raw-expressions
Whenever I want to convert SQL query to Laravel I always change one column name, the laravel error report will show your current query and u can compare it to the SQL query
I want to get the null expiry date result. My whereRaw is working fine but when I used orWhereNull, I get an error. Here is my code:
$offer_details = #\App\Offer::where('store_id',$store_id)->whereRaw('expiry_date > now()')->orWhereNull('expiry_date ')->get();
Following query should work for you as, I don't thing 'orWhereNull()' available in laravel :
$offer_details = #\App\Offer::where('store_id',$store_id)->
->whereNull('expiry_date')
->orWhereRaw('expiry_date > now()')
->get();
Unlike that the "or" variant of 'whereRaw()' is availble as 'orWhereRaw()'.
More details of : whereRaw / orWhereRaw
The whereRaw and orWhereRaw methods can be used to inject a raw where clause into your query. WhereRaw() is a function of Laravel query builder which puts your input as it is in the SQL query's where clause.
I got this query written out in Laravel query builder, bu when i run it, it returns this error: Call to a member function join() on float
$avgYield= DairyCropYield::avg('moisture')
->join('dairy_crops','dairy_crops.id','=','dairy_crop_yields.dairy_crop_id')
->join('dairy_crop_varieties','dairy_crops.dairy_crop_variety_id','=','dairy_crop_varieties.id')
->where('dairy_crop_varieties.crop','=',$crop->crop)
->whereYear('harvested_at','=',Carbon::now()->year)
->get();
But when i write the same query in mySql it wroks as exptected:
SELECT AVG(moisture) FROM dairy_crop_yields AS yield JOIN dairy_crops AS crop ON crop.id = yield.dairy_crop_id JOIN dairy_crop_varieties AS variety ON variety.id = crop.dairy_crop_variety_id WHERE variety.crop = 'corn' AND YEAR(harvested_at) = 2015
Any thoughts / suggestions on what I am not doing right in Laravel query builder.
I do want to master and stick with Laravel's query builder.
Thanks.
Put the avg after the get(), the avg method works on a collection. So what you want is to get() all the result first then only call the avg('moisture') on the available results.
$avgYield= DairyCropYield::join('dairy_crops','dairy_crops.id','=','dairy_crop_yields.dairy_crop_id')
->join('dairy_crop_varieties','dairy_crops.dairy_crop_variety_id','=','dairy_crop_varieties.id')
->where('dairy_crop_varieties.crop','=',$crop->crop)
->whereYear('harvested_at','=',Carbon::now()->year)
->get()
->avg('moisture');
Alternately, you can also do something like this using DB::raw
$avgYield= DairyCropYield::select(DB::raw('AVG(moisture)'))
->join('dairy_crops','dairy_crops.id','=','dairy_crop_yields.dairy_crop_id')
->join('dairy_crop_varieties','dairy_crops.dairy_crop_variety_id','=','dairy_crop_varieties.id')
->where('dairy_crop_varieties.crop','=',$crop->crop)
->whereYear('harvested_at','=',Carbon::now()->year)
->get();
How can I get date from "2015-07-31 06:03:21" using Laravel query builder?
In normal query using DATE() we can get date easily, but I don't know how to use DATE() in Laravel query builder. Please check my code sample given below and correct me?
Normal Query
SELECT DATE('2015-07-31 06:03:21'), customer_id FROM customer_histories
Laravel Query Builder
$customerhistory = Customerhistory::where('customer_id', 1)
->select('freetext', 'DATE(created_at)')
->get();
You can do this with DB::raw(), though if you are only selecting it, why not just take created_at complete? By default, Eloquent will convert the created_at and updated_at columns to instances of Carbon so you can handle it like this in your code:
$customerhistory = Customerhistory::where('customer_id', 1)
->select('freetext', 'created_at')
->get();
dd($customerhistory[0]->created_at->toDateString());
You can use DB::raw('something') for that. In this case your raw input will be treated as part of actual SQL.
This is something you might wanna give a try:
$customerhistory = Customerhistory::where('customer_id', 1)
->select('freetext', DB::raw('DATE(`created_at`)'))
->get();
More details and yet another example cal be found here.
Also it looks like you're using eloquent. You might wanna check the mutators section.
$customerhistory = Customerhistory::where('customer_id', '=', '1')
->select('freetext', DB::raw('DATE(`created_at`)'))
->get();
Thanks.
I am newbie on Laravel, I have a proper SQL Statement (which works on PHPMyAdmin and Navicat) and I can get results. What i want to do is, I want to take that statements in Laravel without using DB::raw();.
Any Helps will be appreciated.
Select
rmm.message,
count(rmm.message) as number,
receivedTime as time
FROM
rcs rcs, rmm rmm
WHERE
rmm.smsCid = rcs.smsCid AND rmm.receivedTime LIKE '%2013-04-01%' AND length('rmm.message') > '3'
GROUP BY(rmm.message)
Alternatively you can use the Fluent Query Builder. Here's my attempt, of course it's not checked as I don't have your data structure to hand. Hopefully enough to get you started:
DB::table('rcs') // SELECT FROM rcs
->join('rmm', 'rmm.smsCid', '=', 'rcs.smsCid') // Simple INNER join
->where('rmm.receivedTime', 'LIKE', '%2013-04-01%')
->where(DB::raw('LENGTH(rmm.message)'), '>', 3)
->get(array(DB::raw('COUNT(rmm.message)'), 'rmm.message', 'receivedTime')); // Get only the columns you want
You can use DB::query() to run your query. This calls the query method on the active DB connection.