mon*_*onk 7 php mysql orm laravel
默认情况下,我们通常按ID号搜索db表上的任何条目.但我找不到如何通过名称列搜索任何条目.
这是我查找条目并将其呈现以供查看的代码
控制者:作者
class Authors_Controller extends Base_Controller {
public $restful = true;
public function get_view($id){
$authorModel = Authors::find($id);
return View::make('authors.view')
->with('author', $authorModel)
->with('title', $authorModel->name);
}
}
Run Code Online (Sandbox Code Playgroud)
型号:作者
<?php
class Authors extends Eloquent {
public static $table = 'authors';
}
Run Code Online (Sandbox Code Playgroud)
路线:
Route::controller(Controller::detect());
Route::get('author/(:any)', array('as'=>'author', 'uses'=>'authors@view'));
Run Code Online (Sandbox Code Playgroud)
查看:
@layout('main.index')
@section('content')
<h1>{{$author->name}}</h1>
<p>
{{$author->bio}}
</p>
<small>
{{$author->created_at}} |
{{HTML::link(URL::$base.'/authors/', 'Go back')}}
</small>
@endsection
Run Code Online (Sandbox Code Playgroud)
我如何使网址不显示ID,但显示帖子的名称
some.com/category/name(而不是some.com/category/id)
Dav*_*ker 23
在您的控制器中,您总是会$id
按照您的Eloquent查询使用搜索:
$authorModel = Authors::find($id);
Run Code Online (Sandbox Code Playgroud)
由于您的命名路由可以提供int或string(:any),因此在控制器上$id
运行类型检查,并根据结果运行不同的查询.
public function get_view($id)
{
if (is_numeric($id))
{
$authorModel = Authors::find($id);
}
else
{
$column = 'name'; // This is the name of the column you wish to search
$authorModel = Authors::where($column , '=', $id)->first();
}
return View::make('authors.view')
->with('author', $authorModel)
->with('title', $authorModel->name);
}
Run Code Online (Sandbox Code Playgroud)
我希望能帮助你.
作为旁注,您的Eloquent模型.
如果使用正确的命名约定,则无需提供表名.
class Author extends Eloquent {
}
Run Code Online (Sandbox Code Playgroud)
请注意,单数Author
将映射到一个Authors
自动调用的表,无需您的任何干预.