为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
陪伴而非守候 2024-01-19 16:53:48
我正在尝试将 Laravel 5.8 Eloquent 与自定义函数和原始 sql 一起使用我有一张桌子Question(id  integertitle stringdescription 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] => )
查看完整描述

1 回答

?
宝慕林4294392

TA贡献2021条经验 获得超8个赞

你不需要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 用法的误解。

我想这就能解决空的问题了!


查看完整回答
反对 回复 2024-01-19
  • 1 回答
  • 0 关注
  • 32 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信