2014-01-29 121 views
2

我有属于模型Product一个Trend如何验证Laravel 4中是否存在数据库关系?

class Product extends Eloquent { 

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

} 

,并作为我的验证规则的一部分,我想确认这种关系存在,如果不使用触发错误:

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

if ($validator->fails()) 
{ 
    ... some redirection code here 

被调用。我试图使用下面的验证exists,但它永远不会启动。

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

我也曾尝试在exists方法有一些变化,但没有人似乎火。我知道我正在测试的实例肯定是并不是有一个关系集。

我在这里做错了什么?

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

+0

我不认为这是可能的与Laravel的内置验证福nctionality。你的'存在:趋势'只是检查趋势本身的存在,而不是关系(它不知道任何关系)。 –

+0

您可以使用趋势的id值填充表单中的隐藏字段吗?然后你可以用整数规则来验证它。 – duncmc

+0

您是否定义了产品和趋势之间的关联? –

回答

7

我有一个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); 
} 

当然,这ExchangeRate类也有协会定义:

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

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

而这一切粘在一起就像一个时钟:

$validator = $exchangeRate->getValidator(); 

if ($validator->fails()) 
    throw new ValidationException($validator); 
+0

这看起来不错!我会尽快尝试... – koosa

+0

然后让我知道任何事情。 –

+0

我最终使用了这个和[这个方法]的组合(http://daylerees.com/trick-validation-within-models) – koosa