date method in eloquent querybuilder - laravel

i have this raw query and i want to use it in eloquent query builder
but seems i cant use date method in eloquent and gave me this error im new in eloquent. what is the problem:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'date(prizes.created_at), user_id' in 'group statement' (SQL: select user_id,COUNT(user_id), date(created_at) from `prizes` group by `date(prizes`.`created_at), user_id` having `user_id` = 1 order by `date(created_at)` desc)
raw SQL:
SELECT
user_id,COUNT(user_id), DATE(created_at) FROM prizes
GROUP BY DATE(prizes.created_at), user_id
HAVING user_id = 1
ORDER BY DATE(created_at) DESC
limit 2
Eloquent:
$points = \App\Prize::selectRaw('user_id,COUNT(user_id), date(created_at)')
->groupBy("date(prizes.created_at), user_id")
->orderBy("date(created_at)","DESC")
->having("user_id","=",1)
->get();
what is the the cleanest and best form??

By default, Laravel tries to parse all strings as tables. This means it will add the string between `.
To avoid this, you can put the string in a DB:raw() function to let Laravel know not to parse this string and send it as-is to the database.
->orderBy(\DB::raw("date(created_at)"), "DESC")
Or use the raw method for ordering:
->orderByRaw('date(created_at) desc')

Related

array datatype from database to eloquent laravel

I have data stored in a database with a column data type of array. I can get the value in PostgreSQL as follows:
select id, student, subject[1] as first_subject, subject[array_length(subject, 1)] as last_subject
from tableinfo
So, I need to get the first and last value of the array in the Laravel eloquent query. But using select in eloquent doesn't seem to work.
Eloquent query:
DB::Table('tableinfo')
->select('id', 'name', 'subject[array_length(subject, 1)] as last_subject')
->get();
Error message I got:
You can not use custom/raw select using select method, but you can use selectRaw method like below:
DB::Table('tableinfo')
->select('id', 'name')
->selectRaw('subject[array_length(subject, 1)] as last_subject')
->get();
above code will generate query like below:
select "id", "name", subject[array_length(subject, 1)] as last_subject from "tableinfo"

Laravel Eloquent: how to use “where” with WithCount to select Models whose count is larger than a number

Suppose I have two tables: posts and tags. I want to eager load all the tags with posts whose post count is larger than 10. How would I do it?
I tried the following but not work:
Tag::withCount('posts')
->where('posts_count', '>' , 10)
->get();
It gives me the following error:
Column not found: 1054 Unknown column 'posts_count' in 'where clause' (SQL: select `tags`.*, (select count(*) from `posts` inner join `post_tag` on `posts`.`id` = `post_tag`.`post_id` where `tags`.`id` = `post_tag`.`tag_id`) as `posts_count` from `tags` where `posts_count` > 1 order by `posts_count` desc)
try this:
Tag::withCount('posts')->having('posts_count', '>' , 10)->get();
If you want to filter on aggregates, you need to use having.

How to solve Laravel union queries with different number of columns

I have two tables contact_us and upload_new_car.
contact_us table contains columns:
id
name
email
phone
message
created_at
updated_at
upload_new_car contains columns:
id
name
phone_number
car_name
car_price
location
car_model_year
car_model
variant
driven
fuel
transmission
city
no_of_owners
upload_1
upload_2
upload_3
upload_4
upload_5
created_at
updated_at
How can I get the UNION of these tables in Laravel? Please help
Not allowing to different size of columns is not laravel's businuess. It is a matter of SQL .You can follow [this link] for more info about UNION statements .
On the other hand for laravel you can use those syntax using union (We can benefit from selecting the same count of columns from each tables).
$first = DB::table('contact_us')
->select('name','phone');
$users = DB::table('users')
->select('name','phone_number as phone')
->union($first)
->get();
dd($users)

get both by ID and Name in laravel?

In MySQL Database Table there are 2 columns
Order TypeID
Order Type
In Order to find a record with ID, I am using below code.
$OrderType = \App\Models\OrderType_Model::find($request->input('OrderTypeID'));
Is there any way to get both by ID and Name ?
You can use a orWhere clause
$orderType = OrderType_Model
->where('OrderTypeId',$request->input('OrderTypeId))
->orWhere('OrderType', $request->input('OrderType))
->first();
$OrderType = \App\Models\OrderType_Model
::where("OrderTypeID", "!=", $request->input('OrderTypeID'))
->where("OrderType", '=', $request->input('OrderType'))->first();

Select rows having 2 columns equal value in laravel Query builder

I want to write a query which selects rows where 2 attributes from 1 entity have equal value.
This would be an example of doing this in raw SQL:
Select * from users u where u.username = u.lastname
Does laravel have any methods that take 2 column names as parameters and return the matching results?
What you need is a DB::raw expression:
DB::table('users')
->where('username', '=', DB::raw('lastname'))
->get();
The only thing DB::raw actually does is to tell the query interpreter not to treat 'lastname' like any other string value but just interpolate it in the SQL as it is.
http://laravel.com/docs/queries#raw-expressions
In Laravel 5, there's now whereColumn for this, for cleaner code:
Users::whereColumn('username', 'lastname')->get();

Resources