我的应用程序有两个数据库连接:
mysql_default_connection => default_database
mysql_custom_connection => custom_database
我在使用Laravel unique
验证方面遇到了一些问题。
protected $connection = 'mysql_custom_connection';
protected $table = 'aluno';
public $rules = [
'email' => 'required|email|unique:custom_database.aluno'
];
当我尝试保存新模型时,唯一的规则可以正常运行,但是当从aluno
中检索某些模型并尝试将其保存为:
$aluno = Aluno::find(1);
$aluno->attribute = 'new value';
$aluno->save();
此日志:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'default_database.aluno' doesn't exist (SQL: select count(*) as aggregate from `aluno` where `email` = aluno3@email.com and `id` <> 50)
如果我从验证中删除unique
规则,请正常工作。
特别是,我无法理解为什么要查询Table 'default_database.aluno'
,因为此数据库不是上面的模型连接。
有人可以向我解释为什么会这样吗?
我的连接配置
'connections' => [
'mysql_default_connection' => [
'driver' => 'mysql',
'host' => 'localhost',
'port' => 3306,
'database' => 'default_database',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
],
'mysql_custom_connection' => [
'driver' => 'mysql',
'host' => 'localhost',
'port' => 3306,
'database' => 'custom_database',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
],
];
'default' => 'mysql_default_connection',
aluno模型的相关部分
protected $connection = 'mysql_custom_connection';
protected $table = 'aluno';
public $rules = [
'nome' => 'required|between:5, 45',
'email' => 'required|email|unique:custom_database.aluno|max:64'
];
此规则适用于创建新模型
解
我正在使用实施Laravel的OctoberCMS,这个问题是OctoberCMS的麻烦而不是Laravel,对不起。要对模型进行验证,我们需要使用10月验证特性,使$rules, $attributeNames and $customMessages
数组调用Validator::make()...
。
在这个特性中,10月只是忽略验证时的模型连接
/**
* Instantiates the validator used by the validation process, depending if the class is being used inside or
* outside of Laravel.
* @return \Illuminate\Validation\Validator
*/
protected static function makeValidator($data, $rules, $customMessages, $attributeNames)
{
return Validator::make($data, $rules, $customMessages, $attributeNames);
}
并且
/*
* Hand over to the validator
*/
$validator = self::makeValidator($data, $rules, $customMessages, $attributeNames);
所以,我确实需要改变
protected static function makeValidator($data, $rules, $customMessages, $attributeNames,$connection = null)
{
$validator = Validator::make($data, $rules, $customMessages, $attributeNames);
if($connection !== null) {
$validator->getPresenceVerifier()->setConnection($connection);
}
return $validator;
}
并且
$validator = self::makeValidator($data, $rules, $customMessages, $attributeNames,$this->connection);
现在就像一个魅力
$rules = [
'email' => 'required|unique:aluno'
];
答案 0 :(得分:0)
从验证中删除default_database,试试这个
public $rules = [
'email' => 'required|email|unique:aluno'
];
如果要指定自定义连接
,请尝试此操作public $rules = [
'email' => 'required|email|unique:mysql_custom_connection.aluno'
];
答案 1 :(得分:0)
试试这个
$rules = [
'email' => 'unique:mysql_custom_connection.aluno,email'
];
它有效,我现在已经尝试过了。只要了解aluno是表,就需要检查唯一的FIELD not table。