查询返回一个对象而不是数组

时间:2019-06-19 13:02:44

标签: laravel

我写了一个模型函数,必须给我所有带有用户ID的帖子,但是它返回一个模型对象。 我的模特:

public static function my_posts(){

    $userId = Auth::id();
    $getPosts = DB::table('posts')->where('user_id',$userId)->get();
    return $getPosts;
}

我的控制器功能:

public function myPosts(){
        $getPosts = new posts_model();
        $getPosts->my_posts();
        return view("myposts",["posts" => $getPosts]);
    }

如何解决此错误?

1 个答案:

答案 0 :(得分:1)

请您更改型号

public static function my_posts(){
    $userId = Auth::id();
    $getPosts = Post::where('user_id',$userId)->get();
    return $getPosts;
}

然后更改您的控制器

public function myPosts(){
    $getPosts = new posts_model();
    $data = $getPosts->my_posts();
    return view("myposts", ["posts" => $data]);
}