dpxua26604 2019-02-10 21:38
浏览 216
已采纳

数据透视表上的HasMany使用了错误的ID

I have a ManyToMany relationship between Election and Party to connect parties to multiple elections.

public function parties(): BelongsToMany
{
    return $this
       ->belongsToMany(Party::class)
       ->using(ElectionParty::class)
       ->withPivot('has_no_answers', 'published', 'program_pdf', 'program', 'id');
}

On the pivot table election_party I added an auto incrementing id.

Parties can give answers to each election, for which reason I created a hasMany relationship to Answer on the pivot table, referenced by electionparty_id

class ElectionParty extends Pivot
{
  public function answers(): HasMany
  {
    return $this->hasMany(Answer::class);
  }
}

Now, to get the answers or in this case it's count, i do this in Blade:

@foreach($election->parties as $party)
    {{ $party->pivot->answers->count() }}
@endforeach

This however, does not work, because it does not try to get answers by the pivot table id, which I assumed it would be but by the id of the election:

SQLSTATE[42703]: Undefined column: 7 ERROR: column answers.election_id does not exist LINE 1: select * from "answers" where "answers"."election_id" = $1 a... ^ HINT: Perhaps you meant to reference the column "answers.question_id". (SQL: select * from "answers" where "answers"."election_id" = 16 and "answers"."election_id" is not null)

Am I missing something here or doing something not how it's supposed to be done?

  • 写回答

1条回答 默认 最新

  • dongzhao3040 2019-02-10 22:16
    关注

    The default keys are generated differently in pivot models. Specify the foreign key:

    class ElectionParty extends Pivot
    {
        public function answers(): HasMany
        {
            return $this->hasMany(Answer::class, 'electionparty_id');
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析