Reputation: 5093
So I'm trying to learn Kohana, and I've hit quite a snag when it comes to their ORM module. When trying to set up a one-to-many ORM object, I am able to update/insert the information from my parent model, but it won't allow me to associate ( insert/update ) any new children.
For clarity's sake, here is my database structure...
recipes
--id
--recipe
--directions
--servings
ingredients
--id
--recipe_id
--amount
--serving
items
--id
--item
...my models...
class Model_Recipe extends ORM
{
protected $_has_many = array( 'ingredient' => array() );
}
class Model_Ingredient extends ORM
{
protected $_belongs_to = array( 'recipe' => array() );
protected $_has_one = array( 'item' => array() );
}
class Model_Item extends ORM
{
protected $_belongs_to = array( 'ingredient' => array() );
}
...and my controller...
class Controller_Recipe extends Controller
{
function action_save_form()
{
$recipe = ORM::factory( 'recipe', 1 );
$recipe->ingredient->recipe_id = 1;
$recipe->ingredient->amount = 1;
$recipe->ingredient->measurement_type = 'tablespoon';
$recipe->ingredient->save();
$recipe->ingredient->item->item = 'butter';
$recipe->ingredient->item->ingredient_id = $recipe->ingredient->id;
$recipe->ingredient->item->save();
}
}
I freely admit this is due to my ineptitude, but I've been over the docs/wiki/read(ing) through the source code, and haven't been able to find anything even close. Appreciate any help/ideas everyone may have
EDIT: After re-reading, it may not be very clear. What I am trying to do, is update the $recipe object, and then update/add ingredients, and their one-to-one sub-objects ( items ) like so:
Upvotes: 0
Views: 2750
Reputation: 7042
As Austin pointed out, has many relations should be plural by convention.
Another thing you're missing is filling has many relations with data; there is no sense in doing it the way you're trying but rather:
function action_save_form()
{
$recipe = ORM::factory('recipe', 1);
// Create an ingredient and attach it to the recipe (one-to-many)
$ingredient = ORM::factory('ingredient')->values(array(
'amount' => 1,
'measurement_type' => 'tablespoon',
'recipe' => $recipe, // sets the fk
));
$ingredient->create();
// Update all ingredients?
foreach ($recipe->ingredients->find_all() as $ingredient)
{
$ingredient->amount = 2;
$ingredient->update();
}
// Create an item and attach to the recipe (one-to-one)
$item = ORM::factory('item')->values(array(
'item' => 'butter',
'ingredient' => $ingredient,
));
$item->create();
// Update the recipes' item after it's been created
$ingredient->item->item = 'chocolate';
$ingredient->item->update();
}
Note: this example doesn't catch ORM_Validation_Exceptions, which should be performed in order to get validation errors.
Upvotes: 3
Reputation: 475
For $_has_many, you should pluralize.
Instead of:
protected $_has_many = array( 'ingredient' => array() );
try:
protected $_has_many = array( 'ingredients' => array() );
Upvotes: 3