【问题标题】:Using Eloquent to retrieve data shows different array使用 Eloquent 检索数据显示不同的数组
【发布时间】:2015-06-21 12:15:31
【问题描述】:

嗯,我对 Laravel 非常陌生。所以我实际上是在学习 Laracast 的基础知识。我有一张叫songs的表,型号Song.php如下:

<?php namespace App;
use Illuminate\Database\Eloquent\Model as Eloquent;

class Song extends Eloquent{

}

还有一个控制器SongsController.php

use App\Song;
use DB;

class SongsController extends Controller
{
    function index() {
        $songs      = Song::get(); 
        $songs2     = DB::table('songs')->get();dd($songs2);
        //$mysong2    = Song::whereSlug('as-long-as-you-love-me')->first(); 
    }
}

所以我希望 $songs$songs2 相同并产生相同的结果。但dd($songs) 产生如下结果:

Collection {#146 ▼
  #items: array:1 [▼
    0 => Song {#147 ▼
      #connection: null
      #table: null
      #primaryKey: "id"
      #perPage: 15
      +incrementing: true
      +timestamps: true
      #attributes: array:6 [▼
        "id" => "1"
        "title" => "As Long as you Love me"
        "slug" => "as-long-as-you-love-me"
        "lyrics" => null
        "created_at" => "2015-06-21 00:00:00"
        "updated_at" => "2015-06-21 00:00:00"
      ]
      #original: array:6 [▶]
      #relations: []
      #hidden: []
      #visible: []
      #appends: []
      #fillable: []
      #guarded: array:1 [▶]
      #dates: []
      #dateFormat: null
      #casts: []
      #touches: []
      #observables: []
      #with: []
      #morphClass: null
      +exists: true
    }
  ]
}

$songs2 产生(我认为是实际的,但不确定):

array:1 [▼
  0 => {#145 ▼
    +"id": "1"
    +"title": "As Long as you Love me"
    +"slug": "as-long-as-you-love-me"
    +"lyrics": null
    +"created_at": "2015-06-21 00:00:00"
    +"updated_at": "2015-06-21 00:00:00"
  }
]

所以我想知道我应该使用哪一个?我做错了什么吗?

【问题讨论】:

    标签: sql eloquent laravel-5


    【解决方案1】:

    没有错。
    对于 $songs,您正在使用带有函数 get() 的 eloquent,该函数将始终返回类型为
    Illuminate\Database\Eloquent\Collection 的对象
    但是对于 $songs2,您使用的是带有函数 get()query builder,它总是会返回一个数组 stdClass 个对象。
    这就是为什么您会看到不同的结果。
    两者都是正确的,你可以同时使用,但是如果你已经为你的歌曲创建了一个模型,那么使用 eloquent 而不是查询构建器。

    【讨论】:

      猜你喜欢
      • 2019-12-09
      • 1970-01-01
      • 2015-01-25
      • 2019-03-04
      • 2021-02-16
      • 1970-01-01
      • 1970-01-01
      • 2016-12-06
      相关资源
      最近更新 更多