在Laravel中使用find()检索数据库对象
我正在学习Laravel4从头开始的教程。教程4:数据库访问描述了从数据库检索数据的几种方法 特别是我不能去工作: 在我的routes.php中,我有在Laravel中使用find()检索数据库对象,laravel,laravel-4,Laravel,Laravel 4,我正在学习Laravel4从头开始的教程。教程4:数据库访问描述了从数据库检索数据的几种方法 特别是我不能去工作: 在我的routes.php中,我有 Route::get('/', function() { $bottle = DB::table('bottle')->find(1); dd($bottle); }); 唯一的输出是“哎呀,好像出了什么问题。”第页。在我的数据库的瓶子表中,主键的名称是瓶子ID。我想这与问题有关,但我找不到有关如何更改find()参数的任何信息。
Route::get('/', function()
{
$bottle = DB::table('bottle')->find(1);
dd($bottle);
});
唯一的输出是“哎呀,好像出了什么问题。”第页。在我的数据库的瓶子表中,主键的名称是瓶子ID。我想这与问题有关,但我找不到有关如何更改find()参数的任何信息。那么如何使用“find”从数据库返回对象呢
以下代码不起作用:
// returns everything from bottle table
$bottles = DB::table('brewery')->get();
return $bottles;
// returns all data for the bottle with an ID of 10
$bottle = DB::table('bottle')->where('bottle_ID', '=', 10)->get();
return $bottle;
// returns all ales from the database
$bottles = DB::table('bottle')->where('beer_type', '=', 'Ale')->get();
return $bottles;
在查询生成器(
DB::table()…
)中使用时,find()
方法将主键列硬编码为id
:
public function find($id, $columns = array('*'))
{
return $this->where('id', '=', $id)->first($columns);
}
您应该改为使用where()
和first()
:
或者,如果决定使用,可以指定键列名:
class Bottle extends Eloquent {
protected $primaryKey = 'bottle_ID';
}
然后像这样检索模型:
$bottle = Bottle::find(1);
非常感谢。我试过了你的两个建议,都成功了!看起来我怀疑自己的列名是对的,但我真的不知道该怎么办。我以前一直在调查MAMP/Laravel配置问题,但那是一条死胡同。
$bottle = Bottle::find(1);