2016-09-24 61 views
-1

我有一個場景,我試圖驗證新的聯繫人可以有多個電子郵件地址添加到他們 - 但每個聯繫人只能有一個特定的電子郵件地址類型。驗證模型只有一種類型的關係在Laravel 5

I.e.我想創建聯繫人電子郵件地址,但他們必須具有「工作」的電子郵件地址類型郵箱地址。他們可以有零個電子郵件地址或多個電子郵件地址,但始終(也是唯一)一個工作電子郵件地址

我的模特們在下面。請注意,電子郵件地址可能與聯繫人以外的對象有關,因此是morphMany。

Contact.php

public function emailaddresses() 
{ 
    return $this->morphMany('EmailAddress', 'emailaddressable'); 
} 

EmailAddress.php

public function emailaddressable() 
{ 
    return $this->morphTo(); 
} 

public function emailaddresstype() 
{ 
    return $this->belongsTo('EmailAddressType', 'email_address_type_id', 'id'); 
} 

EmailAddressType.php

public function emailaddresses() 
{ 
    return $this->hasMany('EmailAddress', 'email_address_type_id', 'id'); 
} 

我使用Laravel 5.1。任何關於從哪裏開始的指針都會很棒。

感謝

回答

0

創建存儲的電子郵件地址function storeEmail(),例如對象模型中的功能。

其中,檢查輸入的電子郵件地址類型。如果您正在使用的模型已包含該類型的關聯電子郵件,則爲默認值。否則,存儲給定類型的地址。

function storeEmail($type, $address){ 
    //Check if the type exists within the retrieved object 

    //If it already exists or if the object is missing a work email, default 

    //Otherwise add the data to the database for the given object 
} 

當模型初始構建時,您可以爲第一個輸入添加所需的工作電子郵件。