【发布时间】:2017-04-03 14:55:28
【问题描述】:
在 Laravel 5.4 中,我正在尝试建立多对多关系。但belongsToMany 返回空!这是我的迁移和模型。
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表中。另外,不相关的是,从迁移来看,您没有使用外键。 -
2 注释:从关系中移除 get() 并添加外键以添加约束
-
@devk 当然!我有数据!在另一个项目中,我做同样的事情,没关系!
-
我会支持@Christophvh 的建议,但除此之外,您粘贴的所有内容看起来都是正确的。所以我认为问题不在于您的代码。也许包括三个数据库表的内容(或每个表中的至少一条记录)将有助于证明您正在使用的数据是有效的。谢谢!
-
你能显示正在使用的查询来获取数据吗?
标签: laravel laravel-5 eloquent