使用辅助函数在Laravel 4中使用DB:raw更改查询的字段

时间:2013-08-14 23:49:17

标签: laravel laravel-4 eloquent

我有一个查询功能,我用来从我的数据库中提取一些数据。我还有一个在“created_at”字段周围更改的功能,就像这样打印:月日YY'

这是查询功能:

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();

该函数位于文件夹helper中,名为“StringEdit.php”。该函数是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;

}

我已经能够在其他地方调用此功能,所以我知道它有效。如何在此上下文中使用它来更改我的“created_at”字段?运行时我收到错误:

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

编辑:新错误:

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

1 个答案:

答案 0 :(得分:0)

这不会像您在查询中使用它的方式那样起作用

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

此处,getDate函数被视为mysql函数且无效,无论如何,您可以使用mysql的原生DATE_FORMAT函数,例如

DATE_FORMAT(fanartists.created_at, "%M %d %y") as created_at

Check the documentation.