gpt4 book ai didi

php - 如何在 Eloquent Laravel 中使用名称查找条目?

转载 作者:可可西里 更新时间:2023-11-01 06:39:06 25 4
gpt4 key购买 nike

默认情况下,我们通常通过 ID 号搜索数据库表中的任何条目。但我找不到如何按名称列搜索任何条目。

这是我用于查找条目并将其呈现以供查看的代码

Controller :作者

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

如何使url不显示id而是显示帖子的名称

some.com/category/name (instead of some.com/category/id)

最佳答案

在您的 Controller 中,您总是会按 $id 进行搜索,因为您的 Eloquent 查询使用:

$authorModel = Authors::find($id);

由于您的命名路由可以提供一个 int 或字符串 (:any),因此在 Controller 中对 $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 的表,无需您进行任何干预。

关于php - 如何在 Eloquent Laravel 中使用名称查找条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12087098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com