2016-04-30 84 views
0

我已經創建了兩個表,第一個是Posts表,第二個是Comments表。 我正在使用sqlite數據庫。結果爲空

在Post Model中,我使用hasMany方法得到的評論函數的結果爲空。

帖子表遷移文件:

class CreatePostsTable extends Migration 
{ 
    /** 
    * Run the migrations. 
    * 
    * @return void 
    */ 
    public function up() 
    { 
     Schema::create('Posts', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->string('name'); 
      $table->timestamps(); 
     }); 
    } 

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

評論表遷移文件:

​​3210

郵政型號:

class Post extends Model 
{ 

    // 
    public function comment(){ 
    return $this->hasMany(Comment::class);  
    //I have also tried: return $this->hasMany(Comment::class,'post_id','id'); 
    } 
} 

的數據已經在表和我都被輸入我在做什麼時得到結果

$post=new App\Post; 
$post->get(); 

但是,當我試圖讓使用

$post->comment; 

後所有的評論我得到

=>Illuminate\Database\Eloquent\Collection {#633 
all:[], 
} 

爲什麼會出現空的結果呢?

回答

0

你不是。你得到一個空的Collection對象。這意味着您的帖子找不到任何結果。

你可以做$post->comment->count() === 0並且成功。

您的關係出現錯誤。你說過你嘗試過別的東西;那看起來更加正確,按照文檔。
https://laravel.com/docs/5.0/eloquent

return $this->hasMany('App\Comment', 'foreign_key', 'local_key');

有了這個,如果你仍然得到一個空集作爲回報,我會鼓勵你安裝Laravel調試工具欄,並檢查了原始的SQL是跑了。您的數據或者不正確,或者有一些問題未在您的帖子中解釋。

編輯:您還可以嘗試在評論中設置belongsTo關係以獲得較好的度量。