Laravel 不能使用 Eloquent/Builder 类型的对象作为数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26781486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:23:29  来源:igfitidea点击:

Laravel cannot use object of type Eloquent/Builder as array

mysqllaraveleloquent

提问by Gui O

As i'm now working with laravel, i have to display some data on the interface. But Laravel is installed on the computer X, and the database is on a distant Y server. For testing purpose, i am trying to display simple data from a table, the first information of the following table :

因为我现在正在使用laravel,所以我必须在界面上显示一些数据。但是 Laravel 安装在计算机 X 上,数据库在远程Y 服务器上。出于测试目的,我试图从表中显示简单数据,下表的第一个信息:

Table site: code_sitevarchar(255) primary key

站点code_sitevarchar(255) 主键

So, this is how i made it :

所以,这就是我做到的:

database.php

数据库.php

'mysql' => array(
    'driver'    => 'mysql',
    'host'      => '126.x.x.x',
    'database'  => 'MYNET',
    'username'  => 'mynet',
    'password'  => 'mypassword',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
    'port'      => '3308',
),

model/Site.php

模型/站点.php

<?php

class Site extends Eloquent {
<empty because i don't need relations for now> }

routes.php

路由文件

Route::model('site', 'Site');
Route::get('liste_sites', array('uses' => 'HomeController@liste_sites', 'as' => 'liste_sites'));

liste_sites.blade.php

liste_sites.blade.php

@for ($i = 0 ; $i < count($sites); $i ++)
    <p>{{$sites[$i]->code_site}}</p>
@endfor

HomeController.php

家庭控制器.php

public function liste_sites() 
    {
        $sites = Site::select('code_site')
        ->orderBy('code_site','desc');

        return View::make('liste_sites', array( 'sites' => $sites, 'which_actif' => 1));
    }

But i get the error

但我得到了错误

Cannot use object of type Illuminate\Database\Eloquent\Builder as array

Is it because my data are not readable ?

是不是因为我的数据不可读?

回答by Tim Lewis

Change this line:

改变这一行:

$sites = Site::select('code_site')->orderBy('code_site','desc');

to this:

对此:

$sites = Site::select('code_site')->orderBy('code_site','desc')->get();

I'm pretty sure that should fix it.

我很确定应该解决它。

Basically, until you call one of the closing functions ->get(), ->paginate(10)or ->first()$sites is treated as a Query, and not an array of Siteobjects, and as such can't be used in a view. Hope that helps!

基本上,除非您调用一个关闭函数->get()->paginate(10)否则->first()$sites 被视为查询,而不是Site对象数组,因此不能在视图中使用。希望有帮助!