Laravel 软删除唯一列名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26424294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:17:34  来源:igfitidea点击:

Laravel Soft Delete Unique column name

phplaraveluniquesoft-delete

提问by Alankar More

Suppose I have category table and I have used soft delete on it. Now first time I have added one category "Test" after that I have delete this category so it will update my deleted_atcolumn from the database.

假设我有类别表,并且在其上使用了软删除。现在我第一次添加了一个类别“测试”,之后我删除了这个类别,这样它就会deleted_at从数据库中更新我的列。

Now when again I am trying to add category with name "Test" it is saying me that this name has been taken. I have tried with rules which are posted Here.

现在,当我再次尝试添加名为“Test”的类别时,它告诉我该名称已被使用。我已尝试使用此处发布的规则。

But it is not working. I have used trait in my model. Below is my model code.

但它不起作用。我在我的模型中使用了 trait。下面是我的模型代码。

<?php
namespace App\Models;

use Illuminate\Support\Facades\Validator as Validator;
use Illuminate\Database\Eloquent\SoftDeletingTrait;

class Category extends \Eloquent {

    use SoftDeletingTrait;

    protected $dates = ['deleted_at'];

    /**
     * Guarded fields which are not mass fillable
     *
     * @var array
     */
    protected $guarded = array('id');

    /**
     * Name of the table used
     *
     * @var string
     */
    protected $table = 'travel_categories';

    /**
     * Validating input.
     *
     * @param array $input
     * @return mixed (boolean | array)
     */
    public static function validate($input, $id = null) {
        $rules = array(
            'name' => array('required','min:2','max:100','regex:/[a-zA-z ]/','unique:travel_categories,name,NULL,id,deleted_at,NULL'),
            'description' => 'Required|Min:2',
            'image' => 'image'
        );
        if ($id) {
            $rules['name'] = 'Required|Between:3,64|Unique:travel_categories,name,'.$id;
        }

        $validation = Validator::make($input,$rules);

        return ($validation->passes())?true : $validation->messages();
    }
}

回答by Seiji Manoan

Did you understand the soft deleting purpose? It will only flag the data to be inactive. It will be there though.

你了解软删除的目的吗?它只会将数据标记为非活动状态。不过它会在那里。

So, if you define the values of that column must be unique, it is right you could not create other one alike.

因此,如果您定义该列的值必须是唯一的,那么您就不能创建其他相同的值。

  • If it needs to be unique, so you should restoreand updatethe data.
  • If it can have many ones, so you should remove the unique key applied on it (and call it by relationship for instance).
  • 如果它需要是唯一的,那么你应该restoreupdate数据。
  • 如果它可以有很多,那么你应该删除应用在它上面的唯一键(例如通过关系调用它)。

Look at: Laravel Eloquent Soft Deleting

看:Laravel Eloquent 软删除

回答by hannesvdvreken

First: I don't understand a couple of things. Are you trying to validate for create and update? Then why do you allow name to be of length 2 till 100 for creation, and only 3 till 64 for after updates?

第一:我不明白一些事情。您是否要验证创建和更新?那么为什么你允许 name 的长度为 2 到 100 来创建,而在更新后只允许 3 到 64 呢?

Second: I recommend dropping this:

第二:我建议放弃这个:

protected $dates = ['deleted_at'];

I don't see the goal of that.

我看不出这样做的目的。

Third, and I'm getting to the point here, what are you trying to do? I guess, what you are trying to do with this filter 'unique:travel_categories,name,NULL,id,deleted_at,NULL'is to check the uniqueness of the nameamong the active categories. In that case, that should work.

第三,我要说到这里,你想做什么?我想,您尝试使用此过滤器做的'unique:travel_categories,name,NULL,id,deleted_at,NULL'是检查name活动类别之间的唯一性。在那种情况下,这应该有效。

回答by Kaloyan

I know this question is old, but I had a similar issue and I stumbled upon this. I wanted to mention how I fixed it for anyone, who is reading it in the future. The problem I had was that Laravel did not allow me to insert a value in a unique column when there was an old record with the same value, but was deleted using soft_delete.

我知道这个问题很老,但我有一个类似的问题,我偶然发现了这个问题。我想提一下我是如何为将来阅读它的任何人修复它的。我遇到的问题是,当存在具有相同值的旧记录但使用 soft_delete 删除时,Laravel 不允许我在唯一列中插入值。

To summarize, the goal is to ignore old soft deleted records for a unique column when inserting a new record. The solution I found is in the migration for the table. For example, let us assume we have these columns:

总而言之,目标是在插入新记录时忽略唯一列的旧软删除记录。我找到的解决方案是在表的迁移中。例如,让我们假设我们有这些列:

  • category - unique
  • deleted_at - keeps tracks of the deleted rows
  • 类别 - 独特
  • Deleted_at - 跟踪已删除的行

Both should be specified as unique in the migration like so:

两者都应在迁移中指定为唯一,如下所示:

 Schema::create('table_name', function (Blueprint $table) {
        $table->string("category");
        $table->softDeletes();
        $table->unique(["category", "deleted_at"]);
    });

Side note: If you already have the table like I did you need to change the migration and create the table again (obviously the data will be lost):

旁注:如果您已经像我一样拥有表,则需要更改迁移并再次创建表(显然数据会丢失):

  • Remove the table
  • Change the migration
  • Remove the record about it from the migrations table
  • run "php artisan migrate" to create the table again
  • 删除表
  • 更改迁移
  • 从迁移表中删除关于它的记录
  • 运行“php artisan migrate”再次创建表