2017-01-26 21 views
1

私はすべての私のコメントをforeachするとき私はすべての私のコメントを得るが、私はその記事からのコメントだけを見たいと思う...私はどのように私のforeachで行うことができますか?その記事からのコメントを表示

デシベル:atricles

Schema::create('articles', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->integer('userID')->unsigned(); 
     $table->string('title'); 
     $table->string('url'); 
     $table->string('username'); 
     $table->integer('points'); 
     $table->integer('amountComments'); 
     $table->timestamps(); 
    }); 

デシベル:コメントはこの記事入れ

<div class="comments"> 
     @if ($article->amountComments > 0) 
      <ul> 
       @foreach ($comments as $comment) 
        <li> 
         <div class="comment-body">{{ $comment->comment }}</div> 
         <div class="comment-info">Posted by {{ $article->username }} on {{ $comment->created_at }} 
          @if ($comment->user_id == Auth::id()) 
           <a class="btn btn-primary btn-xs edit-btn" 
           href="{{ route('edit_comment', ['comment' => $comment->id]) }}">edit</a> 
           <a class="btn btn-danger btn-xs edit-btn" 
           href="{{ route('delete_comment', ['comment' => $comment->id]) }}"> 
            <i class="fa fa-btn fa-trash" title="delete"></i>delete 
           </a> 
          @endif 
         </div> 
        </li> 
       @endforeach 
      </ul> 
     @else 
      <div> 
       <p>No comments yet</p> 
      </div> 
     @endif       

    </div> 
+1

をあなたはコメントを得ているあなたのコントローラのコードを表示することができますか?あなたはちょうどwhere句を追加する必要があるように思えます。私たちはあなたのモデルの上にormコメントを得ることができます。あなたのコントローラをポストして編集することができます –

答えて

3

この記事へのコメントをどうぞ。異質な関係を使用しない場合は、次のようにしてください。

$comments = Comment::where('articleID', $article->id)->get(); 

もう1つの方法はeager loadingを使用することです。まず、関係を定義します。

$article = Article::with('comments')->find($id); 

とコメントが表示されます:

public function comments() 
{ 
    return $this->hasMany('App\Comment', 'articleID'); 
} 

は、その後、データロード

@foreach ($article->comments as $comment) 
    {{ $comment->comment }} 
@endforeach 
+1

ありがとう、私のモデルで 'articleID' – EnzoTrompeneers

1

から

Schema::create('comments', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->integer('articleID')->unsigned(); 
     $table->string('comment'); 
     $table->timestamps(); 
    }); 

ショーのコメント:

@foreach ($article->comments as $comment) 

そして、あなたの記事のモデルに:

public function comments() 
{ 
    return $this->hasMany('App\Comment', 'articleID'); 
} 

Laravelはあなたのための残りを行います。

は、ここにドキュメントを見てください:https://laravel.com/docs/5.3/eloquent-relationships#one-to-many

をそして、あなたはarticle_id代わりのarticleIDを使用して、Laravelの規則に従うかどうかは容易になるだろう。

+0

私は既に私のモデルで関係を作っていましたが、didntはそれに「articleID」を入れませんでした、ありがとう! – EnzoTrompeneers

+0

問題ありません。それがあなたのために働くならば、同じ問題で他の人を助けるために受け入れられたものとしてマークしてください。 –

+0

私はupvoted、どのように私は受け入れられるとマークできますか?あなたは初心者のために申し訳ありません – EnzoTrompeneers

関連する問題