【问题标题】:Nested Eager loading relationships in LaravelLaravel 中的嵌套渴望加载关系
【发布时间】:2016-08-18 01:33:20
【问题描述】:

我正在使用 Laravel 创建一个论坛软件,并且我正在尝试使用 latestPost 访问在特定主题中发布的最新帖子,如下面我的模型中定义的那样

    public function latestPost() {
        return $this->hasOne('App\Post')->with('thread')->with('author')->latest();
    }

这是App\Post.php中定义嵌套关系的方式

public function author()
{
    return $this->belongsTo('App\User', 'author_id');
}

public function thread()
{
    return $this->belongsTo('App\Thread', 'thread_id');
}

public function topic() {
    return $this->belongsTo('App\Topic');
}

我已经能够访问线程,作者等的帖子没有问题,当我的视图中有{{ $topic->latestPost }}时,它会成功列出包含关系的对象。但是,一旦我尝试显示特定部分,例如 {{ $topic->latestPost->author->username }},我就会收到以下错误:Trying to get property of non-object

在这个特定的视图中,主题是另一个从类别中提取的关系,就像在控制器中使用 @foreach 获得 $topics $categories->topics

public function index() {
  $categories = Category::orderBy('order', 'asc')->get();

  return view('welcome', compact('categories'));
}

这是$categories的转储:http://dumptext.com/H8Nq16ea

【问题讨论】:

  • 你能打印你的这个对象`$categories = Category::orderBy('order', 'asc')->get();` 并把转储数组的结果加起来你的问题吗?跨度>
  • 添加在底部!它很长,所以我把它转储到了 dumptext 上。
  • 你可以添加 ->toArray() 与你的这一行 $categories = Category::orderBy('order', 'asc')->get(); 像这样 $categories = Category::orderBy('order', 'asc')->get()->toArray(); 然后提供转储结果。

标签: laravel laravel-5 eloquent laravel-5.2 blade


【解决方案1】:

也许您想使用嵌套预加载。

更改:return $this->hasOne('App\Post')->with('thread')->with('author')->latest();

对此:return $this->hasOne('App\Post')->with('thread.author')->latest();

我也从未听说过 latest() 和您的退货声明的结尾。也许你可以用 orderBy 试试,如下所示。

`return $this->hasOne('App\Post')->with('thread.author')->orderBy('id')->first;`

如果结果不是你想要的顺序,我猜你可以使用 orderBy('id')->reverse() 函数。让我知道它是否对您有所帮助。

【讨论】:

  • 如果我以这种方式加载关系,我会得到线程的作者而不是帖子的作者。
【解决方案2】:

您应该确保您拥有要显示的最新帖子的作者。否则,如果您不希望每条记录都有一个,您应该尝试:

{{ $topic->latestPost->author ? $topic->latestPost->author->username : 'No author' }}

除而不是:

return $this->hasOne('App\Post')->with('thread')->with('author')->latest();

你可以使用

return $this->hasOne('App\Post')->with('thread','author')->latest();

【讨论】:

  • 感谢您提供有关压缩 with 的提示!不幸的是,我仍然遇到错误。如果我只回显 $topic->latestPost,所有作者信息都在对象中,我似乎无法访问它...
猜你喜欢
  • 2020-05-10
  • 2016-05-31
  • 2019-06-19
  • 2014-02-24
  • 1970-01-01
  • 2020-04-12
  • 2019-07-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多