php – 如何在雄辩的Laravel中使用名字查找条目?
发布时间:2020-12-14 19:38:07 所属栏目:大数据 来源:网络整理
导读:默认情况下,我们通常按ID号搜索db表上的任何条目.但我找不到如何通过名称列搜索任何条目. 这是我查找条目并将其呈现以供查看的代码 控制者:作者 class Authors_Controller extends Base_Controller { public $restful = true; public function get_view($id
默认情况下,我们通常按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); } } 型号:作者 <?php class Authors extends Eloquent { public static $table = 'authors'; } 路线: Route::controller(Controller::detect()); Route::get('author/(:any)',array('as'=>'author','uses'=>'authors@view')); 查看: @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 我如何使网址不显示ID,但显示帖子的名称
在您的控制器中,您总是会按照您的Eloquent查询使用$id进行搜索:
$authorModel = Authors::find($id); 由于您的命名路由可以提供int或字符串(: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); } 我希望能帮助你. 作为旁注,您的Eloquent模型. 如果使用正确的命名约定,则无需提供表名. class Author extends Eloquent { } 请注意,单数作者将自动映射到名为Authors的表,而无需您的任何干预. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |