繁体   English   中英

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

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

我正在关注教程文章和评论。 以下工作正常,但是如何在foreach中获取所有带有商品名称的评论?

型号:文章

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');
}

型号:评论

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');


}

ArticleController中的示例转储:

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

从有关查询关系的文档中

$article = Article::find(1);

echo $article->name;

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

例如,在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