2016-11-10 44 views
0

這個職位表中檢索來自多個表中的數據用ajax

<?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'); 
    } 


} 

這是評價模型

<?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'); 
    } 

} 

在刀片頁面,我可以easilly檢索特定職位像所有評論: 假設我有$崗位作爲後

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

但在阿賈克斯我怎麼能做這個 假設我返回響應() - > json($ posts); 什麼建議嗎?它會幫助我很多

+0

包括JavaScript代碼 – Beginner

回答

0

你不必寫response()->json($posts),你可以簡單地return $posts和Laravel會自動響應轉換成JSON。

關於您確切的問題:當控制器查詢$posts,加with('comment')執行,如:$posts = Post::with('comment')->get()它就會與預取評論返回崗位。 這是Laravel的預先加載,你可以閱讀更多關於它在這裏:https://laravel.com/docs/5.3/eloquent-relationships#eager-loading

+0

我想做到這一點使用AJAX這就是爲什麼我寫響應() - > JSON($職位)這個 – leo