如何:验证Laravel 4中是否存在数据库关系?

koo*_*osa 3 php validation laravel laravel-4

我有一个Product属于a的模型Trend:

class Product extends Eloquent {

    public function trend()
    {
      return $this->belongsTo('Trend');
    }

}
Run Code Online (Sandbox Code Playgroud)

作为验证规则的一部分,我想检查这种关系是否存在,如果没有触发错误,请使用:

$validator = Validator::make(Input::all(), $rules, $messages);

if ($validator->fails())
{
    ... some redirection code here
Run Code Online (Sandbox Code Playgroud)

叫做.我曾尝试使用验证存在像下面,但它永远不会触发.

$rules = array(
    'brand_name'  => 'required|min:3',
    'blurb'       => 'required',
    'link'        => 'required',
    'trend'       => 'exists:trends'
);
Run Code Online (Sandbox Code Playgroud)

我也尝试过这种exists方法的一些变化,但似乎没有任何东西可以解雇.我知道我正在测试的实例肯定没有关系集.

我在这做错了什么?

编辑:我现在看到输入这个,我正在验证输入而不是模型值.我如何实际验证模型实例的属性呢?

Rub*_*zzo 11

我在ExchangeRate类中有以下代码:

/**
 * Return the validator for this exchange rate.
 * 
 * @return Illuminate\Validation\Validator A validator instance.
 */
public function getValidator()
{
    $params = array(
        'from_currency_id' => $this->from_currency_id,
        'to_currency_id'   => $this->to_currency_id,
        'valid_from'       => $this->valid_from,
        'rate'             => $this->rate,
        'organization_id'  => $this->organization_id,
    );

    $rules = array(
        'from_currency_id' => ['required', 'exists:currencies,id'],
        'to_currency_id'   => ['required', 'exists:currencies,id', 'different:from_currency_id'],
        'valid_from'       => ['required', 'date'],
        'rate'             => ['required', 'numeric', 'min:0.0'],
        'organization_id'  => ['required', 'exists:organizations,id'],
    );

    return Validator::make($params, $rules);
}
Run Code Online (Sandbox Code Playgroud)

当然,这个ExchangeRate类也有定义的关联:

public function from_currency()
{
    return $this->belongsTo('Currency', 'from_currency_id');
}

public function to_currency()
{
    return $this->belongsTo('Currency', 'to_currency_id');
}
Run Code Online (Sandbox Code Playgroud)

所有这些粘在一起的工作就像一个时钟:

$validator = $exchangeRate->getValidator();

if ($validator->fails())
    throw new ValidationException($validator);
Run Code Online (Sandbox Code Playgroud)