【发布时间】:2016-02-11 11:10:47
【问题描述】:
我在使用刀片递归部分视图时遇到了困难。除了 comment.blade.php 文件中的递归之外,大部分情况下一切正常。
我知道我需要在 @include('articles.comments.comment', $comment) 周围使用一个 foreach 来再次调用它自己,但我不知道如何调用它。
article_cmets 表:
id
message
user_id
parent_id
created_at
updated_at
app\Article.php 类:
class Article extends Model {
protected $table = 'articles';
protected $fillable = [
'category',
'title',
'permalink',
'synopsis',
'body',
'source',
'show_author',
'published_at'
];
protected $dates = ['published_at'];
public function scopePublished($query)
{
$query->where('published_at', '<=', Carbon::now());
}
public function setPublishedAtAttribute($date)
{
$this->attributes['published_at'] = Carbon::parse($date);
}
public function comments()
{
return $this->hasMany('App\Comments')->where('parent_id', 0);
}
}
app\Comments.php 类:
class Comments extends Model {
protected $table = 'article_comments';
protected $fillable = [
'parent_id',
'message',
];
public function author() {
return $this->belongsTo('App\User');
}
public function children()
{
return $this->hasMany('App\Comments', 'parent_id');
}
public function countChildren($node = null)
{
$query = $this->children();
if (!empty($node)) {
$query = $query->where('node', $node);
}
$count = 0;
foreach ($query->get() as $child) {
// Plus 1 to count the direct child
$count += $child->countChildren() + 1;
}
return $count;
}
}
app\Http\Controllers\ArticlesController.php:
public function show($permalink)
{
$article = Article::where('permalink', '=', $permalink)->with('comments','comments.author','comments.children')->first();
if ($article != null) {
$comments = $article->comments;
return view('articles.show', compact('article','comments'));
} else {
return redirect('/')->with('error', 'This article does not exist.');
}
}
资源\视图\文章\show.blade.php
@if (count($comments) > 0)
<ul>
@foreach ($comments as $comment)
@include('articles.comments.comment', ['comment'=>$comment])
@endforeach
</ul>
@else
no comments
@endif
resources\views\articles\cmets\comment.blade.php
<li>
{{ $comment->message }}
@if (count($comment->children) > 0)
<ul>
@foreach ($comment->children as $child)
@include('articles.comments.comment', ['comment'=>$child])
@endforeach
</ul>
@endif
</li>
当前错误:
Invalid argument supplied for foreach() (View: /var/www/dev.example.com/resources/views/articles/comments/comment.blade.php) (View:
【问题讨论】:
-
您确定将
$comments传递给控制器中的视图吗?return view('articles.show', compact('comments')); -
@OP 我看到你已经扩展了你的赏金。您能否告诉我们更新您的类以使用标准的 eloquent 关系(而不是本地查询)对问题有何影响?
-
好的,在你的帖子中它说你有一个
comments表,但它显示Comment类说$table = "article_comments",你的 cmets 表的实际名称是什么? -
@OP 我做了一些挖掘,看起来刀片中有一个名为
@each的内置方法可以自然地处理其中的一些问题。你可以用我更新的答案试一试。如果这不起作用,我们需要dd($comment->children)看看我们在foreach中添加了哪些 laravel 似乎不喜欢的内容。 -
@Jeff
@each方法返回了同样的错误。将dd()函数放在@foreach中会返回一个字符串“1”。 (非常感谢您的持续努力)
标签: php laravel recursion laravel-5