My main question is, how can i relate those 2 tables together with maybe has_many, but veilingen only has_one veilingvoorkeur. The key is veilingen.id = veilingvoorkeur.vid
Problem where? Kohana also offers the possibility of has_one
:
class Model_veilingen extends ORM {
protected $_has_one = array(
'veilingvoorkeur' => array(
'model' => 'veilingvoorkeur',
'far_key' => 'vid',
),
);
}
Now as relationships have always two sides, you need to define the other as well. belongs_to
is used when there always needs to be something on the other side.
class Model_veilingvoorkeur extends ORM {
protected $_belongs_to = array(
'veilingen' => array(
'model' => 'veilingen',
'foreign_key' => 'vid',
),
);
}
If you are unsure whether to use foreign_key
or far_key
, this answer should help you. Also to explain relationships a little more:
- A
has_one
B: One item from A has either one or no item from B related - A
belongs_to
B: One item from A always has one item from B related
Your query could now be done like this:
$veilings = ORM::factory('veilingen')->order_by('created', DESC')->limit(10)
->find_all();
foreach ($veilings as $veiling) {
$veiling->veilingvoorkeur->find();
print $veiling->veilingvoorkeur->vastprijs;
}
I'm honestly not quite sure what to do if $veiling
as no related veilingvoorkeur
, but it should be possible to do like this (from the idea)
$veilingvoorkeur = $veiling->veilingvoorkeur->find();
if (!empty($veilingvoorkeur))
print $veilingvoorkeur->vastprijs;
I didn't test the code, if it fails somewhere I hope to at least have clarified on how to solve this using relationships.