使用Laravel订购商品逻辑

时间:2019-02-16 18:54:17

标签: laravel laravel-5 laravel-5.7

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

问题1

目前,我正在为数据库中的排序列设置一个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();
    }
}

1 个答案:

答案 0 :(得分:1)

您可以为此使用特征。有关更多详细信息,请参见link

相关问题