从控制器访问模型 - Laravel 4
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17514951/
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
Access Model from Controller - Laravel 4
提问by Guns
I am a newbie to Laravel. Please excuse me if this question sounds kiddish.
我是 Laravel 的新手。如果这个问题听起来很幼稚,请原谅。
I have a model
我有一个模型
class Config extends Eloquent {
public static $table = 'configs';
}
and the controller goes as
和控制器去
class UserController extends BaseController {
Public function getIndex ()
{
$config_items = Config::all ();
var_dump ( $config_items );
return View::make ( 'user.userindex' )
-> with ( 'title', 'User Page' );
}
}
But when i try to access the Config model, i am getting the error:
但是当我尝试访问 Config 模型时,出现错误:
Symfony \ Component \ Debug \ Exception \ FatalErrorException Call to undefined method Illuminate\Config\Repository::all()
Symfony \ Component \ Debug \ Exception \ FatalErrorException 调用未定义的方法 Illuminate\Config\Repository::all()


Please help!
请帮忙!
I know this question could help many Laravel 4 newbies like me and my co-workers, so please help!
我知道这个问题可以帮助像我和我的同事一样的许多 Laravel 4 新手,所以请帮忙!
回答by fideloper
As the commenter pointed out, Configis actually a class that's already defined / used.
正如评论者指出的,Config实际上是一个已经定义/使用的类。
You have two options:
您有两个选择:
Option 1:
选项1:
Namespace your Configmodel:
命名空间您的Config模型:
<?php namespace My\Models;
use Illuminate\Database\Eloquent\Model;
class Config extends Model { ... }
Then in your controller:
然后在您的控制器中:
$config_items = My\Models\Config::all();
Note:If you go with option 1 (I suggest you do), you'll need to set up autoloading for your namespaced library. See this blog article on setting up your own Laravel library with autoloading.
注意:如果您选择选项 1(我建议您这样做),您需要为命名空间库设置自动加载。请参阅这篇关于使用自动加载设置您自己的 Laravel 库的博客文章。
Option 2:
选项 2:
Don't use Configas a model name:
不要Config用作模型名称:
<?php
class Configuration extends Eloquent { ... }
Then in your controller:
然后在您的控制器中:
$config_items = Configuration::all();
Hope that helps!
希望有帮助!
回答by Trying Tobemyself
I think Config is a reserved keyword used by laravel to manage config files, so please try changing the model name to something else
我认为 Config 是 laravel 用来管理配置文件的保留关键字,所以请尝试将模型名称更改为其他名称

