find($id)需要一个id并返回一个模型。如果不存在匹配的模型,则返回nullfindOrFail($id)需要一个id并返回一个模型。如果不存在匹配的模型,则会引发错误, 它会抛出一个error。

first()返回在数据库中找到的第一条记录。如果不存在匹配的模型,则返回nullfirstOrFail()返回在数据库中找到的第一条记录。如果不存在匹配的模型,则会引发错误。它会抛出一个error。

get() 返回与查询匹配的模型集合。

pluck($column)仅返回给定列中值的集合。在以前的Laravel版本中,调用了此方法lists。

toArray() 将模型/集合转换为简单的PHP数组。

get() 后连缀方式添加 getList 方法

先了下这个函数

get_object_vars — 返回由对象属性组成的关联数组

<?php
class Point2D
{
    public $x, $y;
    public $label;

    function __construct($x, $y)
    {
        $this->x = $x;
        $this->y = $y;
    }

    function setLabel($label)
    {
        $this->label = $label;
    }
}

// "$label" is declared but not defined
$p1 = new Point2D(1.233, 3.445);
print_r(get_object_vars($p1));

$p1->setLabel("point #1");
print_r(get_object_vars($p1));
Array
(
    [x] => 1.233
    [y] => 3.445
    [label] => 
)
Array
(
    [x] => 1.233
    [y] => 3.445
    [label] => point #1
)

get() 方法后添加 getList() 方法

具体修改如下:

1、在 /vendor/laravel/framework/src/Illuminate/Support/Collection.php 的 toAarray 方法下,增加一个getList方法。

public function getList(){
    return array_map('get_object_vars', $this->items);
}

2、然后就可以这样来查列表了

<?php

namespace App\Http\Controllers;

use App\TestUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TestController extends Controller
{

    public function modelGet()
    {
        $res=DB::table('test_users')->select('id','name','email')
                                    ->offset(0)->limit(5)
                                    ->orderBy('id', 'desc')->get()->getList();
        return $res;
    }

}

3、返回的正是我所想要的数组,如下图:

[
  {
    "id": 1000000,
    "name": "yuta.nakamura",
    "email": "1519440825taichi16@miyake.jp"
  },
  {
    "id": 999999,
    "name": "uno.maaya",
    "email": "1959210199taichi.hamada@gmail.com"
  },
  {
    "id": 999998,
    "name": "saito.kenichi",
    "email": "1934574857youichi.yamamoto@yahoo.co.jp"
  },
  {
    "id": 999997,
    "name": "takuma91",
    "email": "1841529352ryoshida@hotmail.co.jp"
  },
  {
    "id": 999996,
    "name": "haruka66",
    "email": "1807962710sayuri58@ekoda.jp"
  }
]
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐