Reputation: 3798
I'm trying to find a way to get data from different related tables in Kohana .
I have the file table which is defined as :
class Model_File extends ORM {
protected $_belongs_to = array
(
'student' => array ('foreign_key' => 'student_id' )
);
}
Then the session Table :
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' )
);
}
So there is no direct link between filesession and student ... So i can't add it into the Join of the Filesession (->with('student'))
Currently i'm doing this :
$fileSessions = ORM::factory('filesession')
->with('subject')
->with('teacher')
->with('place')
->with('file')
->where('payment_id','=',$payment_id)
->order_by('sessionDate','DESC')
->find_all();
How can I modify this query to JOIN on the student table ?
In another word ... I just need to add the following :
INNER JOIN students ON students.id = file.student_id
But using the Kohana ORM
Edit (Student Model added)
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' )
);
}
Upvotes: 1
Views: 635
Reputation: 7050
You can use join
and on
just as you would in the DB query builder
$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();
or you can use the $_load_with
property on the file model. It does the loading automatically for you, so you don't need a second with call.
class Model_File extends ORM {
protected $_belongs_to = array
(
'student' => array ('foreign_key' => 'student_id' )
);
protected $_load_with = array('student');
}
When you load the File
model, you can access it by using $file->student
automatically, and on your Filesession
for example, it would be $filesession->file->student
Upvotes: 1