Php 类stdClass的对象无法转换为字符串|透视表

Php 类stdClass的对象无法转换为字符串|透视表,php,laravel-4,Php,Laravel 4,我想显示与特定类别关联的帖子 我有一个预定义类别的表,每个类别都与一个唯一的id关联 我有一个帖子表,我有一个链接两个叫做category_post的透视表 透视表由类别id和post id组成 我想查询pivot表以返回与特定类别id关联的所有post\u id 我的控制器采用所选类别id的参数: public function getCategoryPost($id) { $selectedID = DB::table('category_post')->s

我想显示与特定类别关联的帖子

我有一个预定义类别的表,每个类别都与一个唯一的id关联

我有一个帖子表,我有一个链接两个叫做category_post的透视表

透视表由类别id和post id组成

我想查询pivot表以返回与特定类别id关联的所有post\u 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);

    }
现在我想在blade中显示结果,但只显示帖子的标题:

        @foreach($posts as $post)
        class="post-title"> {{$post->title}} 
        @endforeach   
这就是我所拥有的,我得到以下错误“类stdClass的对象无法转换为字符串”


有什么建议吗?

首先,您应该使用雄辩的语言重新构建您的查询,我建议:

$selectedID = CategoryPost::where('category_id', '=', $id)
->select('post_id')
->first();
因为您在这里只获取一个结果,所以应该首先使用GET函数,而不是GET函数,因为GET会返回一个数组!如果坚持使用Get,则应将代码更改为:

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

在将结果和查询返回到视图之前,您应该使用concider var_转储它们,并查看问题所在:)问候我,如果你需要更多的帮助,请告诉我

$selectedID
是一个对象
Post::find()
将其转换为字符串。只是猜测而已。您应该
var\u dump($selectedID)
$selectedId是一个对象,你确定Post::find()接受对象吗,我不这么认为。您好,谢谢您的回答。。。我只有一个问题,我的CategoryPost表是一个透视表。因此,它没有模型。可以为透视表创建模型吗@考万多