如何在Laravel 5 Eloquent中以文章标题显示foreach中的所有注释

问题描述:

I am following a tutorial Articles and comments. Below works fine, but how do i get all comments with the articlename in a foreach?

Model: Article

namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{  
public function comments() {
    return $this->hasMany('App\Http\Models\Comment');
}
protected $fillable = array('title','body');
}

Model: Comments

namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{  
public function article() {
    return $this->belongs('Article');
}
protected $fillable = array('body','article_id');


}

Example dump in ArticleController:

$items = Article::find(1)->comments()->get();
foreach ($items as $item) {
    print_r($item->body);
}

我正在关注教程文章和评论。 Below工作正常,但我如何获得文章名称的所有评论 在foreach中? p>

模型:文章 p>

 命名空间App \ Http \ Models; 
 
use Illuminate \ Database \ Eloquent \ Model  ; 
 
class文章扩展Model 
 {
公共函数comments(){
返回$ this-> hasMany('App \ Http \ Models \ Comment'); 
} 
 
protected $ fillable = array('  title','body'); 
} 
  code>  pre> 
 
 

模型:评论 p>

  namespace App \ Http \ 模型; 
 
use Illuminate \ Database \ Eloquent \ Model; 
 
class注释扩展Model 
 {
public function article(){
 return $ this-> belongs('Article'); 
} \  nprotected $ fillable = array('body','article_id'); 
 
 
} 
  code>  pre> 
 
 

ArticleController中的示例转储: p>

  $ items = Article :: find(1) - > comments() - > get(); 
foreach($ items as $ item){
 print_r($ item->  body); 
} 
  code>  pre> 
  div>

From the documentation on querying relations

$article = Article::find(1);

echo $article->name;

foreach ($article->comments as $comment) {
    //
}

In the CommentController i dumped for example:

foreach ( $comments as $comment) {
    echo $comment->body.' - '.$comment->article->title.'<br>';
}