gpt4 book ai didi

php - 使用 Laravel 的复杂评论、标签、投票、收藏夹数据库关系

转载 作者:行者123 更新时间:2023-11-29 12:34:20 25 4
gpt4 key购买 nike

我正在尝试通过在 Laravel 4.2 中构建一个小型但复杂的应用程序来学习 HABTM 和多态关系。它接收链接,让用户通过标签、评论、投票、收藏和关注等关键词与内容和彼此进行交互。老实说,我已经为此工作了大约 3 天,感觉就像我只是在泥里旋转轮子。这是分割 -

型号:

User, Link, Tag, Comment, Vote, Favorite, Follow

super 基本用例:

USER -> ACTION   -> TARGET
User -> Submit -> Link, Tag, Comment
User -> Tag -> User, Link
User -> Comment -> User, Link
User -> Vote -> Tag, Comment
User -> Favorite -> User, Link, Tag, Comment
User -> Follow -> User, Tag

(假设)表格:

users            [id, username]
links [id, user_id, url]
tags [id, user_id, text]
commentables [id, user_id, commentable, commentable_id, text] //how do i handle comment replies?
taggables [id, user_id, taggable, taggable_id, weight]
votables [id, user_id, voteable, voteable_od, vote]
favorables [id, user_id, favorable, favorable_id]
followable [id, user_id, followable, followable_id]

从这里开始..我不确定我做得是否正确。我一直沉迷于定义关系的不同方式,我只是想完全理解设计

我的模型文件是什么样的?在什么情况下我可能会使用belongsToMany vs morphToMany?这是正确的方法还是我应该探索使用数据透视表?我希望能得到一些关于我需要学习什么才能正确实现这一点的指示

这是我的 User.php 可能的样子,但我不确定返回实际上应该是什么,因为我不太了解关系的需求

(假设)User.php

usersFavored()    // Users which this User has Favored
usersFollowed() // Users which this User has Followed
linksSubmitted() // Links created by the User in the DB
linksFavored() // ...
tagsOnSelf() // Tags attached to this User by other Users
tagsCreated() // Tags which the User created in the DB
tags() // Tags which the User was the first to attach to a Link
tagsVoted() // Tags on which the User has Voted across the entire site
tagsFavored() // ...
tagsFollowed() // ...
commentsOnSelf() // ...
comments() // Comments across the site
commentsFavored() // ...
votesOnSelf() // ...
votes() // Votes across the site
favorites() // Favorites across the site
follows() // Follows across the site

我觉得我已经接近完成这项工作了。我已经准备好 View 和路线,因为我已经重建了这个项目大约四次。我只需要解决所有这些数据库关系逻辑,这样我就可以让应用程序变得栩栩如生。非常感谢您的意见!

最佳答案

这是我的一些想法

  1. 我真的很困惑是否使用belongsToMany 和morphToMany。但现在,随着我对 Laravel 越来越熟悉,我清楚地意识到 morphToMany 可以做的事情也可以由 ownToMany 完成。所以你只需要掌握belongsToMany。已经足够强大了。但是,如果您想了解这两种关系之间的区别,以下是有关何时应该使用它们的说明。对于belongsToMany,您只想获取一些实体,而不关心它们的状态。但是,如果您需要区分这些实体之间的状态,例如投票(两种类型:赞成票和反对票),您可以使用 morphToMany。
  2. 对于您假设的 User.php,每个函数都应该只返回一个 sql 查询实例。这些函数在 Controller 中使用以获得结果。简而言之,模型中的函数只是很好地包装在 Controller 中使用的不同 SQL 语句。通过这种方式,您可以将业务逻辑与 SQL 选择语句分开。
  3. 在模型中调用函数时,请务必调用->get()以保证sql语句的执行。本质上,模型中的每个函数仅返回一条未执行的sql语句。如果想获取sql语句的结果,需要调用->get()。

希望这有帮助。如果您有更多问题,随时可以提供帮助

关于php - 使用 Laravel 的复杂评论、标签、投票、收藏夹数据库关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27023781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com