Laravel4.2: Eloquent - Use DATE_FORMAT in SQL query - laravel-4

I am trying this simple sql query
SELECT DATE_FORMAT(my_date, '%m-%d-%Y') FROM my_tbl WHERE id = 1
in Eloquent like
$tbl = DB::table('my_tbl');
$tbl->select( 'DATE_FORMAT(my_date, "%m-%d,-%Y")' );
$tbl->where( 'id', "=", 1);
Datatable::query($tbl);
but it accepts as string and throws error:
{"error":{"type":"Illuminate\\Database\\QueryException","message":"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'DATE_FORMAT(arrival, \"%d %M, %Y\")'

Okay I just add DB::raw and it worked :)
$tbl->select( 'DB::raw('DATE_FORMAT(my_date, \'%m-%d-%Y\') AS arrival')' );

Related

Eloquent SELECT "string" AS content_type causes errors

I'm using eloquent query builder in Laravel to help me create the equivalent of
SELECT name,'fund' AS content_type FROM fundraisers
This is what I tried:
$db = DB::table('fundraisers')->select("name,'fund' AS content_type")->get()->toArray();
But I get the error
Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'name,'fund'' in 'field list' (SQL: select `name,'fund'` as `content_type` from `fundraisers`)
What am I doing wrong and how do I fix this?
List the columns you want on select like this:
$db = DB::table('fundraisers')
->select('name', DB::raw("'fund' as content_type"))
//...
Check Laravel docs for more info.

date method in eloquent querybuilder

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')

Laravel 5.2 orderBy relation withCount results in SQL error because of failed attempt to get column instead of count

The goal is to sort my campaigns by views in my filtration, which is why i have an analytics table with relations to my campaigns
My campaign model (The DB name is "ads"):
public function views() {
return $this->hasMany('App\Analytic', 'foreign_id', 'id')->where('foreign_type', '=', 'campaign');
}
The controller of my filtration:
$query = Ad::withCount('views')->with('tags');
$query->where("is_active", "=", 1);
$query->where("status", "=", 1);
$query->orderBy('views_count', 'DESC');
$campaigns = $query->get();
Now the reason for not writing it without the $query-> part, is because the query has lots of if statements depending on filtration settings.
The error im getting:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'views_count' in 'order clause' (SQL: select count(*) as aggregate from `ads` where `is_active` = 1 and `status` = 1 and `from_year` >= 7 and `to_year` <= 88 and `price` >= 1000 and `price` <= 64000 order by `views_count` desc)
The error is it tries to fetch a column, but i can't figuere out why.
If i try to access $campaign->views_count in my blade template, it shows the count just fine.
Thank you for your time, i hope someone can tell me what I'm doing wrong here.
The error you're getting is a result of a count() method not a get().
something like this
$query = Ad::withCount('views')->with('tags');
$query->where("is_active", "=", 1);
$query->where("status", "=", 1);
$query->orderBy('views_count', 'DESC');
$campaignCount = $query->count();
wich replaces the complex select part with:
select count(*) as aggregate
if you need the count() and the get(), do it like this:
$query = Ad::withCount('views')->with('tags');
$query->where("is_active", "=", 1);
$query->where("status", "=", 1);
$campaignCount = $query->count();
$query->orderBy('views_count', 'DESC');
$campaigns = $query->get();

Laravel - select temporary column where temporary column

$search_str = "full name search";
$user = App\User::selectRaw("CONCAT(`f_name`, `l_name`) AS `fullname`")
->where('fullname', 'LIKE', '%$search_str%')
->get();
Based on the code above, the column fullname actually does not exist in DB Table. fullname column is just a temporary column.
But when I use it on where clause, Laravel return an error:
Column not found: 1054 Unknown column 'fullname' in 'where clause'
You can use the CONCAT function in your where filter.
$search_str = "full name search";
$user = App\User::selectRaw("CONCAT(`f_name`, `l_name`) AS `fullname`")
->whereRaw("CONCAT(`f_name`, `l_name`) LIKE '%?%'", [$search_str])
->get();
Use Having for aliases. See below reference link.
https://laravel.com/docs/5.6/queries#ordering-grouping-limit-and-offset

Using a helper function to change a field of a query in Laravel 4 using DB:raw

I have a query function that I am using to pull some data from my database. I also have a function that changes around the "created_at" field to print it like so: Month Day YY'
Here is the query function:
public static function friend_activity_json($start = 0, $number_of_posts = 2) {
$friend_activity = DB::table('fanartists')
->join('fans', 'fanartists.fan_id', '=', 'fans.id')
->join('artists', 'fanartists.artist_id', '=', 'artists.id')
->orderBy('fanartists.created_at', 'DESC')
->select(DB::raw('StringEdit::getDate(fanartists.created_at) as created_at, fans.fbid, fans.first_name, fans.last_name, fans.gender, fans.city, fanartists.artist_id, artists.stage_name'))
->get();
The function is in the folder helpers, in a filed called "StringEdit.php". The function is getDate:
public static function getDate($date) {
$full_date = explode(" ", $date);
$date_pieces = explode("-", $full_date[0]);
$year = substr($date_pieces[0], -2);
$monthNum = $date_pieces[1];
$monthName = date("F", mktime(0, 0, 0, $monthNum, 10));
$final_date = $monthName ." ". $date_pieces[2] ." '".$year;
return $final_date;
}
I have been able to call this function elsewhere, so I know it works. How do I get it to work in this context to change around my "created_at" field? When running this I get the error:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '::getDate(fanartists.created_at) as created_at, fans.fbid, fans.first_name, fans' at line 1 (SQL: select StringEdit::getDate(fanartists.created_at) as created_at, fans.fbid, fans.first_name, fans.last_name, fans.gender, fans.city, fanartists.artist_id, artists.stage_name from `fanartists` inner join `fans` on `fanartists`.`fan_id` = `fans`.`id` inner join `artists` on `fanartists`.`artist_id` = `artists`.`id` order by `fanartists`.`created_at` DESC) (Bindings: array ( ))
EDIT: New Error:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"%M %d %y) as created_at, fans.fbid, fans.first_name, fans.last_name, fans.gende' at line 1 (SQL: select DATE_FORMAT(fanartists.created_at, "%M %d %y) as created_at, fans.fbid, fans.first_name, fans.last_name, fans.gender, fans.city, fanartists.artist_id, artists.stage_name from `fanartists` inner join `fans` on `fanartists`.`fan_id` = `fans`.`id` inner join `artists` on `fanartists`.`artist_id` = `artists`.`id` order by `fanartists`.`created_at` DESC) (Bindings: array ( ))
This won't work like the way you used it in your query here
DB::raw('StringEdit::getDate(fanartists.created_at) as created_at, fans.fbid, fans.first_name, fans.last_name, fans.gender, fans.city, fanartists.artist_id, artists.stage_name')
Here, getDate function is being treated as mysql function and it's not valid, anyways, you can use mysql's native DATE_FORMAT function instead, like
DATE_FORMAT(fanartists.created_at, "%M %d %y") as created_at
Check the documentation.

Resources