简体   繁体   English

PHP到LARAVEL与laravel的fetchAll(PDO :: FETCH_OBJ)等效

[英]PHP TO LARAVEL WHAT IS THE EQUIVALENT OF fetchAll(PDO::FETCH_OBJ) to laravel

I'm trying to write this code in laravel controller. 我正在尝试在laravel控制器中编写此代码。

$messages = $db->query("
SELECT name, message
FROM messages
ORDER BY created ASC
LIMIT 100
");

header('Content-Type: application/json');

echo json_encode(
    $messages->fetchAll(PDO::FETCH_OBJ)
);

but I can't write the ->fetchAll(PDO::FETCH_OBJ) 但我不能写-> fetchAll(PDO :: FETCH_OBJ)

If you are using Laravel, you might want to be using Eloquent to achieve this, however if you don't want to do that I'm going to assume you'll be using the Illuminate query builder. 如果您正在使用Laravel,则可能希望使用Eloquent来实现这一点,但是,如果您不想这样做,我将假设您将使用Illuminate查询构建器。

Your query can be replicated as follows: 您的查询可以复制如下:

$messages = DB::table('messages')
                ->select('name', 'messages')
                ->orderBy('created', 'asc')
                ->take(100)
                ->get();

which you can then json_encode as you are. 然后您可以按原样使用json_encode

if you create a Message model class, you can simply call: 如果创建Message模型类,则可以简单地调用:

$messages = Message::latest('created', 'asc')->paginate(100, ['name', 'message']);

return response()->json($messages);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM