如何在 Laravel Eloquent 中调用 DB 函数并使用分页?

我正在尝试将 Laravel 5.8 Eloquent 与自定义函数和原始 sql 一起使用


我有一张桌子


Question(

id  integer

title string

description text

)

以及控制器中的此功能


public function index()

{

    // go to the model and get a group of records

    //$question = Question::orderBy('id', 'desc')->paginate(3);

    $question = Question::selectRaw(DB::raw('id,title,SUBSTRING(description,0,10) as description'))

        ->orderByDesc('id')

        ->paginate(3);

    return view('questions.index')->with('questions', $question);

}

我的目标是将分页与数据库函数一起使用,如上面的示例。


查询有效,分页有效,返回 3 列id,title但description描述为empty。


组装查询的正确方法是什么?


下面是转储


[original:protected] => Array ( [id] => 20 [title] => text [description] => )


陪伴而非守候
浏览 33回答 1
1回答

宝慕林4294392

你不需要selectRaw(DB::raw('')),只需selectRaw(''):public function index(){     $question = Question::selectRaw('id, title, SUBSTRING(description, 1, 10) AS description'))         ->orderByDesc('id')         ->paginate(3);             return view('questions.index')->with('questions', $question); }更新:我刚刚查看 MySql 文档,看到了这个: A value of 0 for pos returns an empty string.你应该做这个:SUBSTRING(description, 1, 10)这里的问题与 Laravel 无关,是对 MySql 用法的误解。我想这就能解决空的问题了!
打开App,查看更多内容
随时随地看视频慕课网APP