Laravel - 控制器中的未定义属性

时间:2014-07-30 11:19:14

标签: laravel orm eloquent

我试图从带有注释的Threads表中获取行。我这样做:

$posts = threads::where('published', '=', true)->orderBy('published_at', 'desc')->orderBy('created_at', 'desc')->orderBy('id', 'desc')->paginate(5);

$datas = [
        'posts' => $posts,
        'comments' => $posts->comments,
        'count_comments' => count($posts->comments)
];

Laravel回归:

Undefined property:Illuminate \ Pagination \ Paginator :: $ comments

1 个答案:

答案 0 :(得分:1)

你可以这样做:

$posts = threads::with('comments')->where('published', '=', true)->orderBy('published_at', 'desc')->orderBy('created_at', 'desc')->orderBy('id', 'desc')->paginate(5);

$comments = [];

foreach ($post in $posts)
{
    $comments[] = $post->comments;
}

$datas = [
    'posts' => $posts,
    'comments' => $comments,
    'count_comments' => count($comments)
];