【问题标题】:Laravel 5.4 belongsToMany relationship returns emptyLaravel 5.4 belongsToMany 关系返回空
【发布时间】: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


【解决方案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() 会返回空数组。

【讨论】:

  • 你是真正的救世主! :)
  • 对此我感到非常抱歉,但它并没有给我我需要的东西!这给了我所有的候选人,我无法获取投票的用户数量!
  • 你从不质疑你想要特定候选人的陈述。
  • 您可以编辑您的问题并添加您想要的候选人。然后我会更新答案
  • 在另一个项目中,我使用的就像我在问题上写的一样,它对我有用!但在这种情况下,我不知道出了什么问题。我的意思是,例如,当我解雇此代码时:$c = new Botuser; $c->votes(); 它给了我一个与宽度 Botuser 相关的候选人列表!
猜你喜欢
  • 2014-11-23
  • 1970-01-01
  • 1970-01-01
  • 2020-02-02
  • 2020-06-03
  • 2017-09-09
  • 2016-06-21
  • 2020-10-02
  • 2015-02-22
相关资源
最近更新 更多