我没有将Eloquent ORM
用于Laravel 4,并且愿意使用model binding
将我的模型与编辑表单绑定。我的代码如下:
routes.php文件
Route::get('/', 'HomeController@index');
Route::get('exchanges', 'Exchange@index');
//Route::get('details/{exchangeID}', 'Exchange@details');
//add question to make the parameter option
Route::get('details/{exchangeID?}', function($exchangeID = 0)
{
return App::make('Exchange')->details($exchangeID);
});
//Admin Dashboard
Route::get('admin', 'Exchange@dashboard');
//Route::get('admin/exchange/edit/{exchangeID?}', function($exchangeID = 0)
//{
// return App::make('Exchange')->edit($exchangeID);
//});
Route::model('exchange', 'ExchangeModel');
Route::get('admin/exchange/edit/{exchange}', array('uses' => 'Exchange@edit', 'as' => 'exchange.edit'));
控制器方法
public function edit(ExchangeModel $exchange)
{
return View::make('exchangeedit')->with('exchange', $exchange);
查看
{{ Form::model($exchange, array('route' => array('exchange.edit', $exchange->id))) }}
{{ Form::close() }}
模型
public static function all()
{
return DB::select('select * from Exchanges');
}
但是,当我访问时:http://localhost/path/site/public/admin/exchange/edit/4
它认为它是404并重定向到404页面。我哪里错了?
答案 0 :(得分:2)
您的路线模型绑定 Route::model()
正在生成404错误。如果您没有使用Eloquent,路由模型绑定将无法按预期运行而无需额外的工作(主要是确保您所需的类具有find()
方法,这将返回您需要的记录。)
您无需使用路径模型绑定即可使用表单模型绑定。这是两个不同的特征,两者都不依赖于它们。
表单模型绑定不需要Eloquent模型实例。它可以是具有正确属性/键的任何数组或对象。以下是Illuminate\Html\FormBuilder.php
的摘录,负责查找模型属性:
protected function getModelValueAttribute($name)
{
if (is_object($this->model))
{
return object_get($this->model, $this->transformKey($name));
}
elseif (is_array($this->model))
{
return array_get($this->model, $this->transformKey($name));
}
}
object_get()
和array_get()
是Laravel helper functions,如果您想进一步了解它们。
因此,您不需要使用Eloquent模型来使用 form 模型绑定,但在使用 route 模型绑定时,您可能希望使用它。 :)
答案 1 :(得分:0)
不,你不能在没有Eloquent ORM
的情况下使用模型绑定,因为在Route::model()
方法中有这样的东西
if ($model = with(new $class)->find($value))
{
return $model;
}
因此,当您使用以下代码绑定模型
时Route::model('exchange', 'ExchangeModel');
model
类的router
方法做了类似的事情
$model = new $class; // Here $class is your ExchangeModel
$model->find(($value) // The id passed to the url {exchange}
if($model) return $model;
因此,当您未在模型中扩展Eloquent ORM
时,没有find
这样的方法可用,因为Eloquent
是Illuminate\Database\Eloquent\Model
类的别名,{ {1}}方法属于此find
类。
更新:作为替代方案,您可以尝试这样的方法。像你这样在模型中添加Model
方法
find
这样,您仍然可以在表单中使用class Exchange {
public static function find($id)
{
$user = DB::table('users')->where('id', $id)->get();
if($user) {
$user = new \Illuminate\Database\Eloquent\Collection($user);
return $user->first();
}
return false; // or not found exception
}
}
。如果您不想使用Form::model()
方法,则可以更改它但不能使用static
方法调用。
::
因此,在这种情况下,您的路线应该是正常的(没有模型绑定)
public function edit($id)
{
// Manually load the model and pass to view
$exchange = Exchange::find($id);
return View::make('exchangeedit')->with('exchange', $exchange);
}