kohana ORM foreign_key

时间:2012-12-25 17:10:12

标签: php kohana kohana-orm kohana-3.2

我正试图找到一种从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'  )
    );

}

所以filesession和学生之间没有直接联系...所以我不能将它添加到Filesession的加入( - > 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();

如何在student表上将此查询修改为JOIN?

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

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' )
    );

}

1 个答案:

答案 0 :(得分:1)

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

    $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