2017-04-03 82 views
0

在Laravel 5.4中,我試圖建立一個多對多的關係。但belongsToMany返回空!這是我的遷移和模型。Laravel 5.4 belongsToMany relationship returns empty

botusers表:

public function up() 
{ 
    Schema::create('botusers', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->integer('t_id'); 
     $table->string('first_name'); 
     $table->string('last_name'); 
     $table->string('username'); 
     $table->string('mobile'); 
     $table->timestamps(); 
    }); 
} 

候選表:

public function up() 
{ 
    Schema::create('candidates', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->string('name'); 
     $table->string('token'); 
     $table->string('degree'); 
     $table->integer('age'); 
     $table->text('desc'); 
     $table->string('photo_url'); 
     $table->string('cv_url'); 
     $table->timestamps(); 
    }); 
} 

第三表,botuser_candidate表:

public function up() 
{ 
    Schema::create('botuser_candidate', function (Blueprint $table) { 
     $table->integer('botuser_id'); 
     $table->integer('candidate_id'); 
    }); 
} 

和在Botuser模型的votes()方法:

public function votes() 
{ 
    return $this->belongsToMany(Candidate::class)->get(); 
} 

當我火votes()方法返回一個空數組。而且我也測試了波紋管方法,

public function votes() 
{ 
    return $this->belongsToMany(Candidate::class,'botuser_candidate','botuser_id','candidate_id')->get(); 
} 

我在這裏錯過了什麼?我該怎麼辦?

編輯: 我也將外鍵添加到關係,但結果仍然是相同的!

+0

你有數據庫中的數據嗎?在'botuser_candidate'表中。另外,不相干的是,你不會使用外鍵來判斷你的遷移。 – devk

+1

2筆記:從關係中刪除get()並添加外鍵以添加約束 – Christophvh

+0

@devk當然!我有數據!在另一個項目中,我做的是同樣的事情,沒關係! – WebCrawler

回答

1

我建議你卸下belongsToMany

的get()方法,然後用

$c=new App\Candidate; 
$c->with('votes')->get() 

查詢數據庫,如果你仍然想使用$c->votes()那麼你就必須做一些更改功能。讓我們使用範圍來實現它。

public function candidates() 
{ 
    return $this->belongsToMany(Candidate::class,'botuser_candidate','botuser_id','candidate_id'); 
} 

public function scopeVotes($query) 
{ 
    return $query->with("candidates")->get(); 
} 

那麼現在我們就可以調用$v->votes(),它應該返回所有的記錄。

直接在belongsToMany方法上調用get()將返回空數組。

+0

你是一個真正的救星! :) – WebCrawler

+0

我很抱歉,但它並沒有給我我需要的東西!這給了我所有的候選人,我無法取得投票數量衆多的用戶! – WebCrawler

+0

你的問題從不聲明你想要特定的候選人。 – oseintow