YII + beforeSave() +从表行中获取最大值
我正在努力让 Yii Framework 中的 beforesave 以这种方式工作:
当用户发送表单时,beforesave() 应该获取名为“order”的列中的最高数字,并将 order+1 的值插入到当前的“order”中场地。
在这里花了几个小时阅读帖子后,我成功地编译了这个东西:
public function beforeSave()
{
if (parent::beforeSave())
{
if($this->isNewRecord)
{
$criteria->select='max(order) as myMaxOrder';
$get_it= new CActiveDataProvider(get_class($this),
array('criteria'=>$criteria,));
$got_it=$get_it->getData();
$whatweneed=$got_it[0]['myMaxOrder'];
$this->order=(int)$whatweneed+1;
}
return true;
}
else
return false;
}
代码从“order”获取了 MAX,但我真的不知道如何正确处理 YII 的 getData() 方法,所以我 var_dumped 它并看到了我正在寻找的东西就在那里,但我仍然不知道如何访问这个值,除了做
$whatweneed=$got_it[0]['myMaxOrder'];
你能告诉我如何正确地做吗?
i'm struggling to get my beforesave in Yii Framework working this way:
when the user sends the form, beforesave() should fetch the highest number in a column called 'order' and insert a value of order+1 into current 'order' field.
After a few hours spent here reading posts i managed to compile this thing:
public function beforeSave()
{
if (parent::beforeSave())
{
if($this->isNewRecord)
{
$criteria->select='max(order) as myMaxOrder';
$get_it= new CActiveDataProvider(get_class($this),
array('criteria'=>$criteria,));
$got_it=$get_it->getData();
$whatweneed=$got_it[0]['myMaxOrder'];
$this->order=(int)$whatweneed+1;
}
return true;
}
else
return false;
}
The code gets the MAX from 'order' but i really did't know how to deal properly with the YII's getData() method, so i var_dumped it and saw that what i was looking was there but i still don't know how to access this value apart from doing
$whatweneed=$got_it[0]['myMaxOrder'];
Could you tell me how to do it right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您将数据库设置为 Order
id
为主键(无论如何它应该已经是),只需将其设置为“自动增量"。如果您的主键 (id
) 设置了自动增量,那么当您在 Yii 中save()
一个没有id
的模型时,它会自动使用比最大值大一的id
保存它。您根本不需要在beforeSave()
中执行任何操作!它是免费功能。但也许我完全误解了你的问题。也许由于某种原因这不是一个自动递增的主键列。在这种情况下,类似的东西应该可以工作(假设您的模型是订单,并且您的列由于某种原因也称为“订单”):
祝您好运!
If you set up your database so that the Order
id
is the Primary Key (it should already be anyway), just set it to "Auto Increment". If Auto Increment is set on your Primary Key (id
), then when yousave()
a Model in Yii without anid
it will automatically save it with anid
one higher than the max. You won't need to do anything inbeforeSave()
at all! It is free functionality.But perhaps I am totally misunderstanding your question. Maybe this is not an auto-incrementing primary key column for some reason. In that case, something like this should work (assuming your model is Order and you column is also, for some reason, called "order"):
Good luck!