Kohana ORM Aliasing and “Trying to get property of non-object”
-
26-09-2019 - |
Question
I have the following tables in the database:
- teams:
- id
- name
- matches:
- id
- team1_id
- team2_id
I've defined the following ORM models in my Kohana v2.3.4 application:
class Match_Model extends ORM {
protected $belongs_to = array('team1_id' => 'team', 'team2_id' => 'team');
}
class Team_Model extends ORM {
protected $has_many = array('matches');
}
The following code in a controller:
$match = ORM::factory('match',1);
echo $match->team1_id->name; /* <-- */
Is throwing the following error on the linke marked with /* <--- */
:
Trying to get property of non-object
The framework is yielding the value of the foreign key instead of a reference to a Match_Model instance as it should (giving the has_many and belongs_to properties stated).
Am I missing something?
Note: Just in case, I've added the irregular plural 'match' => 'matches'
in application/config/inflector.php
Solution
SOLVED! The Kohana community gave me the answer:
The correct value for the $belongs_to property is:
class Match_Model extends ORM {
protected $belongs_to = array('team1' => 'team', 'team2' => 'team');
}
The documentation states it:
class Blog_Post_Model extends ORM { protected $belongs_to = array('author' => 'user', 'editor' => 'user'); }
The blog_posts database table would have 2 columns now, blog_posts.author_id and blog_posts.editor_id, and both would have values that exist in users.id.
It seems that I've missed that line, :)