[英]How can I access a model from a controller using laravel4?
How can I access a model from a controller using laravel4? 如何使用laravel4从控制器访问模型?
So far I have my controller: 到目前为止,我有我的控制器:
<?php
class GatewayController extends BaseController {
public function getContentAll()
{
$content = Content::getContentAll();
return $content;
}
And my model: 而我的模型:
<?php
class Content extends Eloquent {
protected $table = '_content';
public function getContentAll(){
return 'test';
}
But I get: 但是我得到:
Whoops, looks like something went wrong.
Firstly, Eloquent handles the returning of a model collection. 首先,Eloquent处理模型集合的返回。 You do not need to handle this yourself.
您无需自己处理。 So your model should simply look like this:
因此,您的模型应该看起来像这样:
class Content extends Eloquent {
protected $table = '_content';
}
You can then simply get all your content using this: 然后,您可以使用以下命令简单地获取所有内容:
$content = Content::all();
EDIT: 编辑:
If you want to do stuff with the data in your model, try this: 如果要对模型中的数据进行处理,请尝试以下操作:
class Content extends Eloquent {
protected $table = '_content';
public function modifiedCollection()
{
$allContent = self::all();
$modifiedContent = array();
foreach ($allContent as $content) {
// do something to $content
$modifiedContent[] = $content;
}
return $modifiedContent;
}
}
This should then work: 然后应该可以工作:
$content = Content::modifiedCollection();
Instead of this: 代替这个:
$content = Content::getContentAll();
Try this: 尝试这个:
$content = Content->getContentAll();
^^
Or declare your function as static
, like so: 或者将您的函数声明为
static
,如下所示:
public static function getContentAll(){
return 'test';
}
UPDATE : if you don't want to have a static function
, you should instantiate your class in order to call non-static functions: UPDATE :如果您不想使用
static function
,则应实例化您的类以调用非静态函数:
$c = new Content();
$content = $c->getContentAll();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.