简体   繁体   English

如何在Laravel 5 Eloquent中用文章标题显示foreach中的所有评论

[英]How to show all comments in foreach with article title within Laravel 5 Eloquent

I am following a tutorial Articles and comments. 我正在关注教程文章和评论。 Below works fine, but how do i get all comments with the articlename in a foreach? 以下工作正常,但是如何在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: ArticleController中的示例转储:

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

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: 例如,在CommentController中,我转储了:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM