使用Laravel中的find()来检索数据库对象

时间:2015-02-13 20:44:47

标签: laravel laravel-4

我正在https://laracasts.com/series/laravel-from-scratch处理Laravel 4 From Scratch教程。教程4:数据库访问描述了几种从数据库中检索数据的方法。

特别是我无法开始工作:

在我的routes.php中,我有

Route::get('/', function()
{
  $bottle = DB::table('bottle')->find(1);
  dd($bottle);
});

唯一的输出是"哎呀,看起来出了问题。"页。在我的数据库的bottle表中,主键的名称为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;

1 个答案:

答案 0 :(得分:2)

在查询构建器(DB::table()...)中使用时,find()方法将主键列硬编码为id

public function find($id, $columns = array('*'))
{
    return $this->where('id', '=', $id)->first($columns);
}

您应该使用where()first()

$bottle = DB::table('bottle')->where('bottle_ID', 1)->first();

或者,如果您决定使用Eloquent Models,则可以指定键列名称:

class Bottle extends Eloquent {
    protected $primaryKey = 'bottle_ID';
}

并检索这样的模型:

$bottle = Bottle::find(1);
相关问题