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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28508431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:55:55  来源:igfitidea点击:

Using find() in Laravel to retrieve a database object

laravellaravel-4

提问by acetone

I am working through the Laravel 4 From Scratch tutorial at https://laracasts.com/series/laravel-from-scratch. Tutorial 4: Database Access describes several methods for retrieving data from a database.

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

One in particular I cannot get to work:

特别是我无法上班:

In my routes.php, I have

在我的 routes.php 中,我有

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

The only output is the "Whoops, looks like something went wrong." page. In the bottle table of my database, the primary key has the name bottle_ID. I would guess this has something to do with the problem, but I cannot find any information on how to change the find() parameter. So how do I use 'find' to return an object from my database?

唯一的输出是“哎呀,好像出了点问题。” 页。在我的数据库的bottle 表中,主键的名称为bottle_ID。我猜这与问题有关,但我找不到有关如何更改 find() 参数的任何信息。那么如何使用“查找”从我的数据库中返回一个对象呢?

The following code does work:

以下代码确实有效:

// 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;

回答by lukasgeiter

When used in the query builder (DB::table()...) the find()method has the primary key column hardcoded as id:

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

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

What you should do instead is use where()and first():

你应该做的是使用where()and first()

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


Or if you decide to use Eloquent Modelsyou can specify the key column name:

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

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

And retrieve the model like this:

并像这样检索模型:

$bottle = Bottle::find(1);