[英]Nested Eager loading relationships in Laravel
我正在使用Laravel創建一個論壇軟件,我正在嘗試使用我的模型中定義的latestPost
訪問特定主題中的最新帖子
public function latestPost() {
return $this->hasOne('App\Post')->with('thread')->with('author')->latest();
}
以下是在App\\Post.php
中定義嵌套關系的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
在這個特定的視圖中,主題是另一種關系,它來自Controller中的類似物,並使用@foreach
在$categories->topics
上獲取$topics
@foreach
:
public function index() {
$categories = Category::orderBy('order', 'asc')->get();
return view('welcome', compact('categories'));
}
這是$categories
的轉儲: http : //dumptext.com/H8Nq16ea
也許你想使用嵌套的預先加載。
更改: return $this->hasOne('App\\Post')->with('thread')->with('author')->latest();
對此: return $this->hasOne('App\\Post')->with('thread.author')->latest();
此外,我從未聽說過latest()和return語句的結尾。 也許您可以使用orderBy嘗試它,如下所示。
`return $this->hasOne('App\Post')->with('thread.author')->orderBy('id')->first;`
我猜你可以使用orderBy('id') - > reverse()函數,如果結果不是你想要的順序。 讓我知道它是否幫助了你。
您應確保您擁有要顯示的最新帖子的作者。 否則,如果您希望每條記錄都沒有,那么您應該嘗試:
{{ $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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.