在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();
}
我在这里错过了什么?我该怎么办?
编辑: 我也将外键添加到关系,但结果仍然是相同的!
你有数据库中的数据吗?在'botuser_candidate'表中。另外,不相干的是,你不会使用外键来判断你的迁移。 – devk
2笔记:从关系中删除get()并添加外键以添加约束 – Christophvh
@devk当然!我有数据!在另一个项目中,我做的是同样的事情,没关系! – WebCrawler