![](/img/trans.png)
[英]How to get foreign key name of loaded relationship using laravel eloquent
[英]How to find entry using name in eloquent 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);
}
}
型号:作者
<?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,但显示帖子的名称
some.com/category/name(而不是some.com/category/id)
在您的控制器中,您总是会按照您的Eloquent查询使用$id
进行搜索:
$authorModel = Authors::find($id);
由于您的命名路由可以提供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);
}
我希望能帮助你。
作为旁注,您的Eloquent模型。
如果使用正确的命名约定,则无需提供表名。
class Author extends Eloquent {
}
请注意,单数Author
将自动映射到名为Authors
的表,而无需您的任何干预。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.