首页 文章

Laravel Eloquent /流利

提问于
浏览
9

从Eloquent模型中获取所有行时:

$pin = Pin::all();

我得到一个看起来像这样的数组:

array(2) {
  [0]=>
  object(Pin)#36 (5) {
    ["attributes"]=>
    array(9) {
      ["id"]=>
      string(1) "2"
      ["creator"]=>
      string(1) "1"
    ["original"]=>
    array(9) {
      ["id"]=>
      string(1) "2"
      ["creator"]=>
      string(1) "1"
    }
    ["relationships"]=>
    array(0) {
    }
    ["exists"]=>
    bool(true)
    ["includes"]=>
    array(0) {
    }
  }
}

就像我使用Fluent一样:

$pin = DB::table('pins')->get();

我得到一个没有 "Attribute", "Orginial", "realtionships" ..索引的普通数组 .

我如何使用Eloquent以便返回像FLuent那样的Plain Array?

4 回答

  • 0

    它非常简单 .

    $pins = Pin::get();
    foreach($pins as $p){
     $pin[] = $p->to_array();
    }
    

    或者如果您想发送JSON对象,请尝试使用

    $pins = Pin::all();
    return Response::eloquent($pins);
    

    或者如果要将数组转换为json输出而不是使用

    return Response::json(array('name' => 'Batman'));
    
  • 3

    使用Laravel 4,你可以做到:

    //get all pins from db
    public function index(){
      return Pin::all();
    }
    
    //get specific pin from db
    public function show($id){
      return Pin::find($id);
    }
    

    这将以Json格式返回您的数据

  • 11

    Laravel有一个内置 to_array() 功能,所以你可以做这样的事情 .

    $pins = Pin::all();
    foreach($pins as $pin) {
        $pin_array = $pin->to_array();
        /* Do something with pin array here */
    }
    

    希望有所帮助:D

  • 1

    要么

    $model->original;
    // but still do a foreach loop.
    // Like so
    
    $pins = Pin::all();
    foreach($pins as $pin) {
        $pin_array = $pin->original;
        /* Do something with pin array here */
    }
    

相关问题