【问题标题】:kohana ORM foreign_keykohana ORM foreign_key
【发布时间】:2012-12-11 12:53:38
【问题描述】:

我正在尝试从 Kohana 中的不同相关表中获取数据。

我的文件表定义为:

class Model_File extends ORM {

    protected $_belongs_to = array
    (
    'student' => array ('foreign_key' => 'student_id' )
    );
}

然后是会话表:

class Model_Filesession extends ORM {

    protected $_primary_key = 'id';
    protected $_table_name = 'file_sessions';  


    protected $_belongs_to = array
    (
    'file'       => array ('modele'=> 'file'       , 'foreign_key' => 'file_id'     ),
    'subject'    => array ('modele'=> 'subject'    , 'foreign_key' => 'subject_id'  ),
    'place'      => array ('modele'=> 'place'      , 'foreign_key' => 'place_id'    ),
    'teacher'    => array ('modele'=> 'teacher'    , 'foreign_key' => 'teacher_id'  )
    );

}

所以文件会话和学生之间没有直接联系......所以我不能将它添加到文件会话的加入中(->with('student'))

目前我正在这样做:

        $fileSessions  =   ORM::factory('filesession')
        ->with('subject')
        ->with('teacher')
        ->with('place')
        ->with('file')
        ->where('payment_id','=',$payment_id)
        ->order_by('sessionDate','DESC')
        ->find_all();

如何将此查询修改为在学生表上加入?

换句话说...我只需要添加以下内容:

INNER JOIN students ON students.id = file.student_id

但是使用 Kohana ORM

编辑(添加学生模型)

class Model_Student extends ORM {

    protected $_has_one = array(
    'file' => array(
    'model'       => 'file',
    'foreign_key' => 'student_id',
    ),
    );

     protected $_belongs_to = array
    (
    'level' => array ('foreign_key' => 'level_id' )
    );

}

【问题讨论】:

标签: php kohana kohana-orm kohana-3.2


【解决方案1】:

您可以像在数据库查询构建器中一样使用join 和on

    $fileSessions  =   ORM::factory('filesession')
    ->with('subject')
    ->with('teacher')
    ->with('place')
    ->with('file')
    ->join(array('students','student'))->on('student.id', '=', 'file.student_id')
    ->where('payment_id','=',$payment_id) 
    ->order_by('sessionDate','DESC')
    ->find_all();

或者您可以在文件模型上使用$_load_with 属性。它会自动为您加载,因此您无需再花一秒钟的时间。

class Model_File extends ORM {

  protected $_belongs_to = array
  (
  'student' => array ('foreign_key' => 'student_id' )
  );
  protected $_load_with = array('student');
}

当您加载File 模型时,您可以自动使用$file->student 访问它,例如,在您的Filesession 上,它将是$filesession->file->student

【讨论】:

  • 我认为可以修改模型定义以使其工作。
  • 用你的学生模型定义更新你的帖子,我可能会帮助你。我需要确定你是否使用 ORM 模块的命名约定
  • 我可以从 File 加载学生,当我尝试使用 FileSessions 加载学生时出现问题
猜你喜欢
  • 2011-10-23
  • 2012-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多