首页 > 解决方案 > 雄辩关系上的 toSql() 返回`where id = null`

问题描述

我正在研究 3 维数据透视表

建筑学

我制作了以下表格和模型。

register_colleges( model: RegisterCollege )
- college_id
- random field

programs ( model: Program )
- id
- program_name

courses ( model: Course )
- id
- course_name

course_program_register_college
- course_id
- program_id
- college_id

现在我面临的问题是,null当我尝试访问program_name(比如说)时,我的视图会显示结果。这是我所期望的,因为当我将其转换为 Sql() 时,它会显示以下查询 -

select * from 'programs' inner join 'course_program_register_college' on 'programs'.'id' = 'course_program_register_college'.'program_id' 其中 'course_program_register_college'.'college_id' 为空

我无法弄清楚为什么这个查询试图获取数据where 'course_program_register_college'.'college_id' is null

RegisterCollege.php(模型)

// pivot table is looking for register_college_id as a primary key field
protected $primarykey = 'college_id';

  public function programs(){
    return $this->belongsToMany('App\Program', 
    'course_program_register_college', 'college_id');
  }

编辑:-

雄辩的查询

{{ $college->programs()->toSql() }} // in some view.blade.php

标签: phplaraveleloquentpivot-table

解决方案


推荐阅读