【问题标题】:Undefined eloquent methods find($id)/all()未定义的雄辩方法 find($id)/all()
【发布时间】:2014-03-26 07:47:38
【问题描述】:

我尝试使用 Laravel 和 Eloquent 创建简单的模型。 这是我的代码示例:

composer.json

"laravel/framework": "4.1.*"

routes.php

Route::controller('items', 'ItemsController');
Route::get('item/{item}', array('as'=>'item', 'uses'=> 'ItemsController@getView'));

php工匠路线:

| | GET item/{item}    | item | ItemsController@getView    |    |    |
| | GET items          |      | ItemsController@getIndex   |    |    |

控制器/ItemsController.php

<?php

class ItemsController extends BaseController {
    public function getIndex()
    {
        $items = Item::all();
        return View::make('items.index')
            ->with('title', 'Index show')
            ->with('items', $items);
    }

    public function getView($id)
    {
        return View::make('items.view')
            ->with('title', 'View show')
            ->with('items', Item::find($id));
    }

}

模型/Item.php

<?php

class Item extends Eloquent {

    protected $table = 'items';

}

DB:我有 6 行的 MySQL 表“项目”,例如:

+----+-----------+---------------------+
| id | name      | created_at          |
+----+-----------+---------------------+
|  4 | ironman   | 2012-04-03 10:02:44 |
|  5 | robot     | 2012-04-13 10:02:44 |
+----+-----------+---------------------+

当我尝试 GET mydomain/item/2 Laravel 说:

Call to undefined method Item::find()

然后 GET mydomain/items/

Call to undefined method Item::all()

我错过了什么?

【问题讨论】:

  • 你确定你使用的是 Eloquent 类吗?我不知道 Laravel 但 Eloquent 类应该有 find() 和 all() 方法,除非它定义你必须编写这些方法。 Laravel 需要use namespace\Eloquent 语句吗?
  • 你做了composer dump-autoload吗?
  • @Jorge Laravel 自己做

标签: php laravel eloquent


【解决方案1】:

当我“即时”更改模型和表名称以及执行大量迁移回滚时,有时会发生这种情况。尝试重命名您的模型名称,它在大多数情况下对我有用。

【讨论】:

  • 哇,这解决了我的问题,谢谢!这看起来像一个错误,或者它可能是“缓存”?
  • 你成功了!优秀
猜你喜欢
  • 1970-01-01
  • 2018-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-07
  • 2022-11-23
相关资源
最近更新 更多