Yii2。管理新消息的最佳做法是什么?
Yii2. What is the best practice to manage new messages?
我有 3 个数据库 tables:项目、投票和连接 table project_votes。每个项目可以有很多票。在投票 table 中使用状态列(可能的值为 "new" 和 "old")以区分传入消息是否是个好主意?在我的应用程序中,如果用户打开他自己的项目,所有新消息都应该变旧。我使用以下代码执行此操作:
获得新选票:
public function getNewVotes()
{
return $this->hasMany(Vote::className(), ['id' => 'vote_id'])->where(['like', 'status', 'new'])->via('projVotes');
}
将所有投票设置为旧:
$model->newVotes = 'old'// in Controller
public function setNewVotes($var)// in Model
{
foreach ($this->newVotes as $value) {
$value->status = $var;
$value->update();
}
}
或者没有 foreach 循环有更好的方法吗?例如,将更新与 where 子句一起使用?
我假设用户可以为项目投票。如果是这样,为什么不投票 table.
- 项目(id名称资金)
- vote ( id project_id user_id value ) // value 是一种手段
表决
- 用户(id名)
否则,为什么不在投票中创建一个外键而不是添加一个连接点table。
- 项目(id名称资金)
- 投票(id project_id 价值)
关于你的问题,我会在投票 table 中添加一个布尔字段 'read',默认为 false。
要获取项目的未读投票,请将其添加到项目模型中。
public function getUnreadVotes()
{
return Vote::find()->where([
'project_id' => $this->id,
'read' => false
])->all();
}
为了在获取投票后将投票设置为阅读,您可以使用 updateAll()。
Vote::updateAll(['read' => true], ['project_id' => $this->id]);
我有 3 个数据库 tables:项目、投票和连接 table project_votes。每个项目可以有很多票。在投票 table 中使用状态列(可能的值为 "new" 和 "old")以区分传入消息是否是个好主意?在我的应用程序中,如果用户打开他自己的项目,所有新消息都应该变旧。我使用以下代码执行此操作: 获得新选票:
public function getNewVotes()
{
return $this->hasMany(Vote::className(), ['id' => 'vote_id'])->where(['like', 'status', 'new'])->via('projVotes');
}
将所有投票设置为旧:
$model->newVotes = 'old'// in Controller
public function setNewVotes($var)// in Model
{
foreach ($this->newVotes as $value) {
$value->status = $var;
$value->update();
}
}
或者没有 foreach 循环有更好的方法吗?例如,将更新与 where 子句一起使用?
我假设用户可以为项目投票。如果是这样,为什么不投票 table.
- 项目(id名称资金)
- vote ( id project_id user_id value ) // value 是一种手段 表决
- 用户(id名)
否则,为什么不在投票中创建一个外键而不是添加一个连接点table。
- 项目(id名称资金)
- 投票(id project_id 价值)
关于你的问题,我会在投票 table 中添加一个布尔字段 'read',默认为 false。
要获取项目的未读投票,请将其添加到项目模型中。
public function getUnreadVotes()
{
return Vote::find()->where([
'project_id' => $this->id,
'read' => false
])->all();
}
为了在获取投票后将投票设置为阅读,您可以使用 updateAll()。
Vote::updateAll(['read' => true], ['project_id' => $this->id]);