首页 > 解决方案 > 如何防止发布重复值?

问题描述

我有一个代码可以从一个看起来像这样的表单中发布详细信息。包含Ampang, Kuala Lumpur=的字段area_slug 形式

然后,此表单进入一个控制器,该控制器作为 post 函数将值保存在表中。下面是 post 函数中的代码:


        if ( $this->outlet->locations->count() ) {
            foreach ( $this->outlet->locations as $index => $location ) {

                $area = Level2::find( $locations[ $index ][ 'area_id' ] );
                $area_slug = ( $area ? $area->slug : '' );
                $shipping_fee_value = (float)$locations[ $index ][ 'shipping_fee_value' ];

                // two type of conditional checks
                // $shipping_fee_allow_negotiate = !empty( $location[ 'shipping_fee_allow_negotiate' ] );
                if ( !empty( $locations[ $index ][ 'shipping_fee_allow_negotiate' ] ) ) {
                    $shipping_fee_allow_negotiate = 1;
                } else {
                    $shipping_fee_allow_negotiate = 0;
                }

                /**
                 * Update each location belongs to Outlet
                 * Laravel Model Insert
                 * @see https://laravel.com/docs/8.x/eloquent#updates
                 */
                $location->area_slug = $area_slug;
                $location->shipping_fee_value = $shipping_fee_value;
                $location->shipping_fee_allow_negotiate = $shipping_fee_allow_negotiate;
                $location->update();
            }
        } else {
            foreach ( $locations as $location ) {

                $area = Level2::find( $location[ 'area_id' ] );
                $area_slug = ( $area ? $area->slug : '' );
                $shipping_fee_value = (float)$location[ 'shipping_fee_value' ];

                // two type of conditional checks
                // $shipping_fee_allow_negotiate = !empty( $location[ 'shipping_fee_allow_negotiate' ] );
                if ( !empty( $location[ 'shipping_fee_allow_negotiate' ] ) ) {
                    $shipping_fee_allow_negotiate = 1;
                } else {
                    $shipping_fee_allow_negotiate = 0;
                }

                /**
                 * Create Location and related it to Outlet with `outlet_id`
                 * Laravel Model Insert
                 * @see https://laravel.com/docs/8.x/eloquent#inserts
                 */
                $location = new Location();
                $location->outlet_id = $this->outlet->id;
                $location->area_slug = $area_slug;
                $location->shipping_fee_value = $shipping_fee_value;
                $location->shipping_fee_allow_negotiate = $shipping_fee_allow_negotiate;
                $location->save();
            }
        }

所以我想要实现的是防止area_slug发布相同的内容,例如。Ampang, Kuala Lumpur在这两个Location 1Location 2各自的领域。我有获得前一个的想法,area_slug但我不知道该怎么做。如果有任何不清楚的细节,请发表评论。

标签: phplaravel

解决方案


如果你使用 Laravel 的验证,你可以使用它distinct来确保所有提交位置的唯一性:

$request->validate([
    '*.location' => 'distinct',
]);

推荐阅读