2014-09-03 31 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

相关问题