代码之家  ›  专栏  ›  技术社区  ›  Dan

@foreach上的Laravel分析错误

  •  0
  • Dan  · 技术社区  · 8 年前

    我在看视频 Laravel 5.4 From Scratch: Eloquent Relationships and Comments 并出现以下错误:

    分析错误:语法错误,意外“)”,应为“[”

    当我尝试复制视频并放置以下内容时,我明白了这一点:

    @foreach ($film->comment as comment)
    
    <p>{{$comment->body}}</p>
    
    @endforeach
    

    这是错误页面上突出显示的代码部分:

    <?php $__currentLoopData = $film->comment; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as comment): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
    

    但是当我输出 {{$film->comments}} 它确实给了我一个结果:

    [{"id":1,"film_id":"1","body":"I loved this film!","created_at":null,"updated_at":null}]

    我有一张电影表和评论表。在tinker中,它按我的需要显示,例如。

    >>> $c = App\Comment::first();
    => App\Comment {#751
         id: "1",
         film_id: "1",
         body: "I loved this film!",
         created_at: null,
         updated_at: null,    }
    >>> $c->film;
    => App\Film {#746
         id: "1",
         title: "The Godfather",
         director: "Francis Ford Coppola",
         description: "It stars Marlon Brando and Al Pacino as the leaders of a fictional New York crime family. The story, spanning 1945 to 1955, chronicles the family under the patriarch Vito Corleone (Brando), focusing on the transformation of Michael Corleone (Pacino) from reluctant family outsider to ruthless mafia boss.",
         date: "1972-03-24",
         created_at: null,
         updated_at: null,    }
    

    以下是我的型号:

    注释模型:

    class Comment extends Model
    
    {
        public function film()
        {
            return $this->belongsTo(Film::class);
        }
    }
    

    胶片型号:

    class Film extends Model
    {
        public function comments()
        {
            return $this->hasMany(Comment::class);
        }
    }
    

    非常感谢您的帮助!

    2 回复  |  直到 8 年前
        1
  •  1
  •   Dan    8 年前
    @foreach ($film->comments as $comment)
    <p>{{$comment->body}}</p>
    @endforeach
    
        2
  •  0
  •   emild_    8 年前

    首先确保$film->添加时注释不为空

    @if( count($film->comments) > 0 ) 
       @foreach($film->comments as $comment)
          <p>{{$comment->body}}</p>
       @endforeach
    @endif
    
    推荐文章