我怎么能拒绝重复数据库中的两列


Laravel How can I reject repeat the two column in database

我有一个相同的表:

id | u_id | f_id

,我插入了一些数据,如:

id   = 1;
u_id = 5;
f_id = 8;

我的问题是,如果他试图插入相同的数据,我如何拒绝用户插入?

每当第一次保存新模型时,creatingcreated事件将被触发。如果数据库中已经存在一个模型,并且调用了save方法,则会触发updating/updated事件。但是,在这两种情况下,saving/saved事件都将触发。

例如,让我们在服务提供者中定义一个Eloquent事件侦听器。在事件侦听器中,我们将对给定模型调用isValid方法,如果模型无效,则返回false。从Eloquent事件侦听器返回false将取消save/update操作。
<?php
namespace App'Providers;
use App'YourModel;
use Illuminate'Support'ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        YourModel::saving(function ($yourModel) 
        {
            if ( ! $yourModel->isValid() ) 
                return false;
        });
    }
}

在你的模型添加isValid()函数中,在这个函数中你将添加你的条件:

public function isValid()
{
    if( $this->u_id = 5 && $this->f_id == 8)
        return false;
    else
        return true;
}

注意:我猜id是自动增加的。

希望对你有帮助。