Laravel多foreach

时间:2018-03-11 17:06:50

标签: php laravel loops foreach while-loop

我想得到一个多子评论。

我怎么能不使用foreach(){foreach(){}} ...

我有三种模式:

strony.php 模型

    class Strony extends Model
{
        public function komenty() {
        return $this->belongsToMany('App\Comment', 'taxonomies')->withPivot('parent_id');
    }
    public function sub() {
        return $this->belongsToMany('App\Comment', 'taxonomies', 'parent_id');
    }}

taxonomy.php 模型

class Taxonomy extends Model
{
    protected $table = 'comments';


    public function tax() 
    {
        return $this->belongsToMany('App\Comment','taxonomies', 'parent_id', 'comment_id')->withPivot('parent_id');
    }
}

comment.php 型号

class Comment extends Model
{
public function subcomment() {
        return $this->belongsToMany('App\Comment', 'taxonomies', 'parent_id');
    }
    }

Controller.php这样

echo '<ul>';
foreach($str->komenty as $g) {
$numer = $g->pivot->comment_id;
$child = $g->pivot->parent_id;

if($child == null) {
echo '<li>' . $g->title;

$cmt = Comment::find($numer);

$sub1 = $cmt;

echo '<ul>';
foreach($sub1->subcomment as $sub2) {
    echo '<li>' . $sub2->title . '</li>';

   echo '<ul>';
    foreach($sub2->subcomment as $sub3) {

            echo '<li>' . $sub3->title . '</li>';
            echo '<ul>';
            foreach($sub3->subcomment as $sub4) {
                echo '<li>' . $sub4->title . '</li>';
            }
            echo '</ul>';
    }
    echo '</ul>';
}

echo '</ul>';
echo '</li>';

}
}
echo '</ul>';

表格 这是我的表sql enter image description here

-comment1

- 将comment3

---注释2

--- comment4

---- comment6

- comment5

&#13;
&#13;
<ul><li>comment1<ul><li>comment3</li><ul><li>comment2</li><ul></ul><li>comment4</li><ul><li>comment6</li></ul></ul><li>comment5</li><ul></ul></ul></li></ul>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

不要在控制器中回显HTML代码,请使用观看次数:https://laravel.com/docs/5.6/views

创建两个视图并使用递归包含。

comment.blade.php

<ul>
    @foreach($comment->subcomment as $subcomment)
        <li>{{ $comment->title }}</li>
        @include('comment', ['comment' => $subcomment])
    @endforeach
</ul>

comments.blade.php

<ul>
    @foreach($str->komenty as $comment)
        @if(is_null($comment->pivot->parent_id))
            <li>{{ $comment->title }}</li>
            @include('comment', ['comment' => $comment])
        @endif
    @endforeach
</ul>

答案 1 :(得分:0)

我尝试使用

 foreach($str->komenty as $g) {
$numer = $g->pivot->comment_id;
$child = $g->pivot->parent_id;

if($child == null) {

echo $g->title . '<br>';
$cmt = Comment::find($numer);

$sub2 = $cmt;
$i = 1;
$o = 2;

while($i < 5) {
    $i++;
    $o++;
    if(isset(${'sub'.$i}->subcomment)) {
foreach(${'sub'.$i}->subcomment as ${'sub'.$o}) {
    $num = ${'sub'.$o}->pivot->comment_id;
    echo ${'sub'.$o}->title . '<br>';
}}}}}

它只是最后一个元素。

因为这会使foreach(){} foreach(){}成为foreach(){ foreach(){} }