2017-04-03 84 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