问题
I'm using Eloquent outside laravel framework from https://github.com/illuminate/database. The below is my composer file
{
"require": {
"illuminate/database": "*",
"illuminate/validation": "*",
"dhorrigan/capsule": "*"
}
}
And because of problem in Validator::make(). I'm using one of the suggested method in stackoverflow to use it like
class Validator
{
protected static $factory;
public static function instance()
{
if (!static::$factory) {
$translator = new Symfony\Component\Translation\Translator('en');
static::$factory = new Illuminate\Validation\Factory($translator);
}
return static::$factory;
}
public static function __callStatic($method, $args)
{
$instance = static::instance();
return call_user_func_array(array($instance, $method), $args);
}
}
Now i can validate required, in, etc. But i'm not able to validate unique key index for two or three columns. I tried the https://github.com/felixkiss/uniquewith-validator. But its extended from Validator. It dint work for me. And i'm not sure if laravel has a way to handle validation for composite unique keys. Their examples are not clear in the documentation.
Can you suggest a way to solve the composite unique key validation ?
回答1:
In my case some rules (e.g.: unique) didn't work since you need a presenceValidator set in your factory. I managed it and this is my approach:
Create your own class (MyModel) extending Eloquent model and add this method:
public static function getResolver()
{
return parent::$resolver;
}
in your validator class after namespace (easier names):
use \Illuminate\Validation\Factory as Factory;
use \Illuminate\Validation\DatabasePresenceVerifier as DatabasePresenceVerifier;
use \Symfony\Component\Translation\Translator as Translator;
Finally (I'm not using dhorrigan capsule but it may work):
$translator = new Translator('en');
$container = $capsule->getContainer();
$presenceVerifier = new DatabasePresenceVerifier(MyModel::getResolver());
static::$factory = new Factory($translator, $container);
static::$factory->setPresenceVerifier($presenceVerifier);
Now you can use unique validation rule and other rules based on DB.
Hope it helps!
来源:https://stackoverflow.com/questions/18781555/eloquent-validation-for-composite-unique-key