2016-11-10 1 views
0

를 사용하여 여러 테이블에서 데이터를 검색이 게시물 테이블 인 아약스

<?php 

use Illuminate\Database\Schema\Blueprint; 
use Illuminate\Database\Migrations\Migration; 

class CreateCommentsTable extends Migration 
{ 
    /** 
    * Run the migrations. 
    * 
    * @return void 
    */ 
    public function up() 
    { 
     Schema::create('comments', function (Blueprint $table) { 
      $table->increments('id'); 

      $table->integer('user_id')->unsigned(); 
      $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); 

      $table->integer('prf_id')->unsigned(); 
      $table->foreign('prf_id')->references('id')->on('profiles')->onDelete('cascade'); 

      $table->integer('post_id')->unsigned(); 
      $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade'); 

      $table->longText('comment'); 
      $table->integer('like')->unsigned(); 
      $table->timestamps(); 
     }); 
    } 

    /** 
    * Reverse the migrations. 
    * 
    * @return void 
    */ 
    public function down() 
    { 
     Schema::drop('comments'); 
    } 
} 

이 게시물 모델

<?php 

    namespace App; 

    use Illuminate\Database\Eloquent\Model; 

    class Post extends Model 
    { 
     protected $table='posts'; 
     protected $fillable = ['status']; 
    protected $hidden = []; 

    public function profile(){ 
     return $this->belongsTo('App\Profile', 'prf_id'); 
    } 

    public function user(){ 
     return $this->belongsTo('App\User'); 
    } 

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


} 

이 내가 easilly 같은 특정 게시물의 모든 코멘트를 검색 할 수 있습니다 블레이드 페이지에서 댓글 모델

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Comment extends Model 
{ 
    protected $table='comments'; 
    protected $fillable = ['comment','like']; 


    protected $hidden = []; 

    public function post(){ 
     return $this->belongsTo('App\Post', 'post_id'); 
    } 

    public function profile(){ 
     return $this->belongsTo('App\Profile', 'prf_id'); 
    } 

    public function user(){ 
     return $this->belongsTo('App\User'); 
    } 

} 

입니다 : 난 후

@foreach ($post->comment as $comment) 
{{$comment->comment}} 

하지만 아약스에서 $ 게시물을 가지고 가정 내가 어떻게 할 수 do 내가 대답 반환 응답() -> json ($ posts); 어떤 제안? 그것은 당신이 단순히 return $posts 및 Laravel 자동으로 JSON으로 응답을 변환 할 수 있습니다, 저에게 많은

+0

이 자바 스크립트 코드 – Beginner

답변

0

당신은 response()->json($posts)를 작성하지 않아도 도움이 될 것입니다.

정확한 문제 : 컨트롤러에서 $posts을 쿼리 할 때 with('comment') 실행을 추가하면 다음과 같이 표시됩니다. $posts = Post::with('comment')->get() 그러면 댓글 프리 페치가있는 게시물을 반환합니다. 그것은 Laravel의 열망 로딩, 당신은 여기에 대한 자세한 내용을보실 수 있습니다 : https://laravel.com/docs/5.3/eloquent-relationships#eager-loading

+0

을 포함 나는 응답() 쓰기 왜 아약스 그게 전부를 사용하여이 작업을 수행 할 수 -> JSON ($ 게시물)이 – leo