使用where子句Eloquent选择一列

时间:2016-06-09 16:09:51

标签: laravel eloquent

我正在使用Eloquent。但我在理解Eloquent语法方面遇到了麻烦。我一直在寻找,并尝试这个备忘单:http://cheats.jesse-obrien.ca,但没有运气。

我如何执行此SQL查询?

SELECT user_id FROM notes WHERE note_id = 1

谢谢!

2 个答案:

答案 0 :(得分:3)

如果您想要一条记录,请使用

Note::where('note_id','1')->first(['user_id']);

并且使用多个记录

Note::where('note_id','1')->get(['user_id']);

答案 1 :(得分:0)

如果'note_id'是模型的主键,您只需使用:

Note::find(1)->user_id

否则,您可以使用任意数量的语法:

Note::where('note_id', 1)->first()->user_id;
Note::select('user_id')->where('note_id', 1)->first(); 
Note::whereNoteId(1)->first();
// or get() will give you multiple results if there are multiple

另请注意,在任何这些示例中,您还可以将整个对象分配给变量,并在以后需要时抓取user_id属性。

$note = Note::find(1);
// $user_id = $note->user_id;