Kohana 3 Updating/Adding Related Entries
I'm currently writing an application using Kohana 3.2, which is great, however the documentation leaves something to be desired.
I have a recipe 开发者_开发知识库model and a rating model, which are related by a has_many and belongs_to. Ratings belong to a recipe, and a recipe has many ratings. I've been able to successfully retrieve a recipe's rating, by finding the rating that corresponds to both the id of the current user and the recipe with a $recipe->ratings->where('user_id', '=', '$user->id'). Once I've retrieved the rating, I'm able to update it successfully.
$recipe = ORM::factory('recipe')
->where('id', '=', $recipe_id)
->find();
$my_rating = $recipe->ratings
->where('user_id', '=', $user->id)
->find();
$my_rating->rating = $rating;
$my_rating->save();
The problem comes in when a rating doesn't already exist. In everything I've searched, I've found that I should probably be using the $recipe->add() function to add a rating, however I continue to get errors. When I try to load the rating, should I run a check that it has found an entry? I feel like there is a way of the ORM to know whether it exists, and if doesn't, it should create it.
The above code will create the new rating, however it will not automatically add the recipe_id to the rating table. Should I be adding the rating to the recipe first?
You should have 'raiting' coumn in your 'recipe' table.
You are doing everithing right.
If you have 'raiting' coumn in your 'recipe' table raiting property ('raiting' coumn) for selected row will be filled with the value of $rating/.
精彩评论