Laravel 验证唯一/存在于不同的数据库连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32728346/
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 12:23:37  来源:igfitidea点击:

Laravel Validation unique/exists with different database connection

laravellaravel-5.1laravel-validation

提问by user3130415

In the documentation, I saw you could set a connection for the unique rule which is great. However, the exists doesn't seem to follow the same logic. Take this for example:

在文档中,我看到您可以为独特的规则设置连接,这很棒。然而,exists 似乎并不遵循相同的逻辑。以这个为例:

$rules = [
    'username'         => 'required|max:40|unique:user',
    'name'             => 'sometimes|required',
    'email'            => 'required|email|max:255|unique:int.user',
    'password'         => 'sometimes|required|confirmed|min:6',
    'password_current' => 'sometimes|required'
];

The unique rule works GREAT in this instance. It uses my database connection called 'int' and calls the user table. HOWEVER, when the rules are reversed like so:

在这种情况下,唯一规则非常有效。它使用我的名为“int”的数据库连接并调用用户表。但是,当规则像这样颠倒时:

$rules['email'] = 'required|email|max:255|exists:int.user';

I got this error:

我收到此错误:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'int.user' doesn't exist (SQL: select count(*) as aggregate from int.user where email = [email protected])

SQLSTATE[42S02]:未找到基表或视图:1146 表“int.user”不存在(SQL:从 int.user 选择计数(*)作为聚合,其中 email = [email protected]

It's trying to call an int.user table instead of using the int database connection.

它试图调用 int.user 表而不是使用 int 数据库连接。

Is there a reason exists doesn't act the same way as unique? Thanks.

存在的原因是否与唯一的行为方式不同?谢谢。

回答by Omar Faruk

instead of using connection name you can try with straight Database name which is defined in "int" connection. faced similar problem and these way worked for me. like

您可以尝试使用在“int”连接中定义的直接数据库名称,而不是使用连接名称。面临类似的问题,这些方式对我有用。喜欢

$rules['email'] = 'required|email|max:255|exists:DB_Name.user';

回答by Daud khan

You can use

您可以使用

'email'           => 'exists:mysql2.users|required'

Where mysql2 is second database settings array in the database.php file

其中 mysql2 是 database.php 文件中的第二个数据库设置数组

回答by Artistan

Ultimately for Laravel 5.6.* you need to look at an existing instance of the model you are trying to validate, or specify ...

最终对于 Laravel 5.6.* 您需要查看您尝试验证的模型的现有实例,或指定...

{db_connection_name}.{schema_name}.{table_name}

{db_connection_name}.{schema_name}.{table_name}

... to ensure that you are looking at the proper table.

...以确保您正在查看正确的表格。

Validation Example

验证示例

validate it...

验证它...

<?php

// for instance... 
//   maybe auth user is in a different db
//   = so you cannot validate with your default db connection
$default_user = Auth::user();

// pass the instance in order to allow Validator to qualify the proper connection/name
\App\Validation\User::validate($_POST, $default_user);

User Validation class

用户验证类

<?php
namespace App\Validation;

class User extends Validator
{
    /**
     * @param \Illuminate\Database\Eloquent\Model|string $mixed
     * @param string $default
     * @return string
     */
    public static function table($mixed,$default='default_connection.app_schema.users_table')
    {
        if($mixed instanceof \Illuminate\Database\Eloquent\Model){
            $table = $mixed->getConnectionName().'.'.$mixed->getTable();
        } else {
            if (! empty($mixed)) {
                $table = $mixed;
            } else {
                $table = $default;
            }
        }
        return $table;
    } 

    /**
     * validation to create a new user
     *
     * @param array $data
     * @param \App\User|string $mixed
     * @return array
     * @throws \Illuminate\Validation\ValidationException
     */
    public static function validate(array $data, $mixed='default_connection.app_schema.users_table'){
        return Validator::validate($data,[
            'username'         => 'required|max:40|unique:'.self::table($mixed),
            'name'             => 'sometimes|required',
            'email'            => 'required|email|max:255|unique:'.self::table($mixed),
            'password'         => 'sometimes|required|confirmed|min:6',
            'password_current' => 'sometimes|required'
        ]);
    }
}