2016-06-09 91 views
0

Im使用Eloquent。但我無法理解Eloquent語法。我一直在尋找,並嘗試這個備忘單:http://cheats.jesse-obrien.ca,但沒有運氣。用where子句選擇一個列Eloquent

我該如何執行此SQL查詢?

SELECT user_id FROM notes WHERE note_id = 1

謝謝!

+0

該SQL查詢完全無效,因爲它缺少'FROM'子句。 – ceejayoz

+0

你可能想要類似'Model :: select('user_id') - > whereNoteId(1) - > get()'。 – ceejayoz

回答

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

如果你想有一個單獨的記錄,然後使用

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

和多個記錄使用

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