使用Laravel订购商品逻辑

问题描述 投票:0回答:1

对于我的Laravel应用程序,我实现了一个排序功能。在选项列表中,我显示了两个按钮(向上和向下),它们在OptionController中上下触发功能(见下文)。

问题1

目前我正在为数据库中的sort-column选择一个DECIMAL(30,15)字段。我随机选择这个30,15。你能给我一个建议吗,DECIMAL(?,?)最适合这种分类领域?

问题2

我想将updown逻辑移动到一个地方,我可以在不同的控制器中使用它与通用模型(例如Sort::up($models, $item)。什么是正确的地方放置这样的逻辑?服务?辅助功能? ...?

问题3

当我创建一个新项目(例如下面的例子中的选项)时,我需要自动将排序设置为最后一项+ 1的排序。当然,我可以在存储它时在控制器中执行此操作,但是我可以将它放入模型本身的逻辑?并且:我可以将这个逻辑放在多个模型中使用它而不重复代码?

namespace App\Http\Controllers;


use App\Models\Option;
use App\Models\Attribute;

class OptionController extends Controller
{

    public function up($id, $attributeId) {
      $options = Attribute::findOrFail($attributeId)->options;
      $option = Option::findOrFail($id);

      foreach ($options as $index => $o) {

        // Search for the current position of the
        // option we have to move.
        if( $option->id == $o->id ) {

          // Will be first element?
          if( $index == 1) {

            // Set the sort to current first element sort - 1
            $option->sort = $options[0]->sort-1;

          } else if( $index > 1) {

            // Get the previous and the pre-previous items from the options
            $pre = $options[$index-1]->sort;
            $prepre = $options[$index-2]->sort;

            $diff = ($pre - $prepre) / 2;

            $option->sort = $prepre + $diff;
          }

          break;
        }
      }

      $option->save();

            Session::flash('message', __(':option moved up.', [ 'option' => $option->name ]));
      Session::flash('message-type', 'success');

      return redirect()->back();
    }

    public function down($id, $attributeId) {
      $options = Attribute::findOrFail($attributeId)->options;
      $option = Option::findOrFail($id);

      foreach ($options as $index => $o) {

        // Search for the current position of the
        // option we have to move.
        if( $option->id == $o->id ) {

          // Will be last element?
          if( $index == count($options)-2 ) {

            // Set the sort to current last element sort + 1
            $option->sort = $options[count($options)-1]->sort+1;

          } else if( $index < count($options)-2) { // ???

            // Get the previous and the pre-previous items from the options
            $next = $options[$index+1]->sort;
            $nextnext = $options[$index+2]->sort;

            $diff = ($nextnext - $next) / 2;

            $option->sort = $next + $diff;
          }

          break;
        }
      }

      $option->save();

      Session::flash('message', __(':option moved down.', [ 'option' => $option->name ]));
      Session::flash('message-type', 'success');

      return redirect()->back();
    }
}
laravel laravel-5 laravel-5.7
1个回答
1
投票

你可以使用一个特征。有关详细信息,请参阅link

© www.soinside.com 2019 - 2024. All rights reserved.