Kohana 3 更新/添加相关条目

发布于 2024-11-30 23:44:21 字数 731 浏览 0 评论 0原文

我目前正在使用 Kohana 3.2 编写一个应用程序,这很棒,但是文档还有一些不足之处。

我有一个食谱模型和一个评级模型,它们通过 has_many 和 Belongs_to 相关。评分属于一个菜谱,一个菜谱有多个评分。我已经能够成功检索食谱的评级,方法是使用 $recipe-> ratings->where('user_id', '=', '$user->id')。检索到评级后,我就可以成功更新它。

    $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();

当评级尚不存在时就会出现问题。在我搜索过的所有内容中,我发现我可能应该使用 $recipe->add() 函数来添加评级,但是我仍然收到错误。当我尝试加载评级时,是否应该检查它是否已找到条目?我觉得 ORM 有一种方法可以知道它是否存在,如果不存在,它应该创建它。

上面的代码将创建新的评级,但它不会自动将recipe_id添加到评级表中。我应该先将评级添加到食谱中吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

感情废物 2024-12-07 23:44:22

你的“菜谱”表中应该有“raiting”栏。

你做的一切都是对的。

如果您的“recipe”表中有“raiting”coumn,则所选行的 raiting 属性(“raiting”coumn)将填充 $ rating/ 的值。

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/.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文