【发布时间】:2015-09-30 07:14:11
【问题描述】:
您好,我正在使用 Laravel 和自定义 CMS 将存储在 CMS 中的一些标签同步到数据库中。此功能工作正常。但是,我想在将它们插入数据库时以数字方式为它们设置顺序,并且如果将新的同步到数据库中,我希望将其作为最后一个值添加到数据库中,即如果有 12 个项目存在新项目将在 order 列中添加为值 12(因为 0 将是第一个值)。我希望在不重置现有订单值的情况下完成此操作。
这是我的存储库中的内容:
public function sync()
{
$tags = $this->client->fetchTags('Status');
$updated = $this->update_tasks($tags);
// remove the rest of the statuses
\Status::whereNotIn('id',$updated->lists('id'))->delete();
}
/**
* Save any tags to the local DB;
* @param $tag
*/
public function update_tags($tags)
{
$return = [];
foreach ($tags as $tag) {
$return[] = $tag->id;
}
$local = \Status::whereIn('cms_tag_id',$return)->get()->toIndexedArray('cms_tag_id');
foreach ($tags as $tag) {
if (isset($local[$tag->id]))
{
$local_doc = $local[$tag->id];
}
else
{
$local_doc = new \Status;
}
$local_doc->updateFromCMS($tag);
$uids[] = $local_doc->cms_tag_id;
}
return \Status::whereIn('cms_tag_id',array_unique($uids));
}
然后在我的模型中我有这个: 状态.php
public function updateFromCMS($tag)
{
$i = 0;
$this->cms_tag_id = $tag->id;
$this->cms_tag_name = $tag->name;
$this->order = $i++;
$this->save();
return $this;
}
但是,这会将订单列中的所有值添加为零,这是不希望的,并且找到的任何新值也将添加为零值。有什么想法可以让我保存这个订单,例如:0-100?
更新
根据@insanebits 的说明,我已将模型更改为以下内容:
public function updateFromCMS($tag)
{
$i = Status::orderBy('order', 'DESC')->pluck('order');
$this->cms_tag_id = $tag->id;
$this->cms_tag_name = $tag->name;
$this->order = $i+1;
$this->save();
return $this;
}
但是,现在这会更改所有行的顺序值。即如果最大值是 5,那么 0 的值将被设置为 6,然后所有的值都将增加 1。因此,设置的顺序将丢失。任何想法我做错了什么??
【问题讨论】:
-
因为每次调用此方法时,它都会在开头使用
$i = 0;。您需要从数据库中检索order值,然后才递增 -
$i = ModelClass::where('order')->orderBy('order', 'DESC)其中模型类是您正在使用的实际模型 -
我的意思是你需要获得最大的相关
order值,它存储在你的数据库中
标签: php database laravel model