2017-08-07 28 views
2

首先請原諒,如果您在閱讀所有您認爲不清楚的問題或應編輯問題時,請進行編輯,我會接受。Laravel:根據ID傳遞的查詢返回數據我通過URL

路線

Route::get('project/{id}', ['uses' => '[email protected]', 'as' => 'admin.projects.show']); 

我想做

渲染兩個表的信息視圖會發生什麼。

表信息

一臺被稱爲項目,我有這個字段:ID,蛞蝓,秩序,公共,pathheader和pathhome。

第二個表稱爲project_translation,其中我有這些字段:id,locale,project_id,title,description。

查詢問題

我需要一個查詢在那裏我得到我通過對URL項目的信息。這將是這樣的(工作):

$project = Project::find($id); 

我打印帶有{{$項目 - >字段名}}

現在,我想用相同的檢索翻譯的數據的數據項目ID。我是用做它:

$translation = ProjectTranslation::find($id); 

當然不過,回到我的ProjectTranslation的數據與我在URL中傳遞的ID。

問題

應該如何看,我得到了project_translations的數據與同PROJECT_ID查詢?

非常感謝,如果需要更多信息或只是不清楚。請發表評論。

+0

你想要它與連接或不同的查詢? – C2486

+0

我更喜歡兩種方式。總是很好的學習新方法。 –

回答

2

剛上ProjectTranslation使用$id找到的所有記錄與project_id等於$id像這樣:

$translation = ProjectTranslation::where('project_id',$id)->get(); 

如果你只是有一個ProjectTranslation記錄,那麼你就可以得到這樣的:

$translation = ProjectTranslation::where('project_id',$id)->first(); 

希望你能理解。

+0

它成功了。謝了哥們。也許在這幾天我會有更多關於查詢的問題。如果您有興趣,請關注我的個人資料。 –

+0

@LluísPuigFerrer恭喜你有解決方案,如果有任何問題隨時問:D:D –

+0

嗨@SagarGautam你在這裏?也許你可以幫我 –

3

試着這樣做:

$project = Project::find($id); 
$translation = ProjectTranslation::where('project_id', $id)->first(); 

做,在控制器,然後你可以將這些數據傳遞給視圖:

return view('sample', ['project' => $project, 'translation' => $translation]); 
+0

完美@Marcin非常感謝您的快速回答。當你這樣做:'where('project_id',$ id)'你正在比較project_id字段和你傳遞的URL的URL是否爲真?可以這樣做:'$ translation = ProjectTranslation :: where($ id,$ project-> id);'?將$ id與項目表的id值進行比較?謝了哥們! –

+0

該函數爲您提供了所有數據庫條目,其中字段'project_id == $ id',然後您可以使用 - > get()獲取條目數組,或者 - > first()如果您想獲取第一個匹配值。 – Marcin

+0

其實我有兩個翻譯爲每個項目。所以應該看起來像:'$ translation = ProjectTranslation :: where('project_id',$ id) - > get();'?所以我需要做一個foreach。 –