【问题标题】:Laravel - Undefined property in a controllerLaravel - 控制器中的未定义属性
【发布时间】:2014-07-30 11:19:14
【问题描述】:

我正在尝试使用 cmets 从 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 返回:

未定义属性:Illuminate\Pagination\Paginator::$cmets

【问题讨论】:

标签: laravel orm eloquent


【解决方案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)
];

【讨论】:

  • 完美解决方案。但是没有自动的解决方案来检索与外键关联的所有表?
猜你喜欢
  • 2017-11-04
  • 1970-01-01
  • 2019-09-21
  • 2014-08-17
  • 1970-01-01
  • 1970-01-01
  • 2018-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多