2014-09-03 118 views
0

我想顯示與特定類別關聯的帖子。類stdClass的對象無法轉換爲字符串|數據透視表

我有一個預先定義的類別表,每個類都與一個唯一的ID相關聯。

我有一個職位表,我有一個數據透視表,鏈接兩個稱爲category_post。

數據透視表由category_id & post_id組成。

我想要查詢數據透視表來恢復與特定category_id關聯的所有post_id。

我的控制器需要所選類別的ID的參數:

public function getCategoryPost($id) 
    { 


     $selectedID = DB::table('category_post')->select(['post_id'])->where('category_id', '=', $id)->get(); 
     $posts = Post::find($selectedID); 

     return View::make('posts.category')->with('posts', $posts); 

    } 

現在我想顯示在葉片上的結果,但該職位的只有標題:

 @foreach($posts as $post) 
     class="post-title"> {{$post->title}} 
     @endforeach 

這是我的,我得到以下錯誤「class stdClass的對象無法轉換爲字符串」

有什麼建議嗎?

+0

'$ selectedID'是一個對象。 Post :: find()把它變成一個字符串。只是一個猜測。你應該'var_dump($ selectedID);'。 – 2014-09-03 09:40:14

+0

** $ selectedId **是一個對象,你確定** Post :: find()**需要對象,我不這麼認爲。 – anwerj 2014-09-03 09:40:23

回答

0

首先應該重建了一下您的查詢中使用雄辯,我建議:

$selectedID = CategoryPost::where('category_id', '=', $id) 
->select('post_id') 
->first(); 

既然你取結果只有一個在這裏你應該先用,沒有得到的功能GET回報你一個數組中!如果你堅持使用Get你應該改變你的代碼如下:

$posts = Post::find($selectedID[0]); // the first element of the response array 

你應該海外商品會有你的var_dump結果和查詢它們返回到視圖之前,看看問題出在哪裏! :)關心並告訴我你是否需要更多幫助!

+0

你好,謝謝你的回答...我只有一個問題,我的CategoryPost表是一個數據透視表。所以沒有它的模型。你可以爲數據透視表創建一個模型嗎? @Cowwando – escGoat007 2014-09-03 09:55:19

相關問題