2015-02-12 66 views
1

我是新來laravel的關係,所以很多道歉,如果它只是愚蠢的問題。我在項目中使用名爲users_email的數據透視表來獲取用戶的電子郵件。數據透視表包含外鍵Uid和Email_id。 Uid引用用戶表 的主鍵和Email_id相同。我可以在使用QueryBuilder加入時得到結果。雄辯如何與關係合作?

$recent_inbox_email=DB::table('users_email')-> 
       join('email','users_email.email_id','=','email.Id')-> 
       join('users','users_email.Uid','=','users.Id')-> 
       where('users_email.Uid','=',$Uid)-> 
       where('email.draft','<>','true')-> 
       where('email.trash','<>','true')-> 
       where('email.status','=','unread')->count(); 

這裏是我如何定義

public function getUid()//User Model 
    { 
     return $this->hasMany("User_Email",'Uid'); 
    } 

    public function getEmId()//Email Model 
    { 
     return $this->hasMany("User_Email",'email_id'); 
    } 
    //User_Email Model 
    public function email() 
    { 
    return $this->belongsTo('Email','Id','email_id'); 
    } 
    public function user() 
    { 
    return $this->belongsTo('User','Id','Uid'); 
    } 

現在我想查詢像這樣用雄辯

$query= select * from users_email inner join 
    email on users_email.email_id=email.Id 
    inner join users on users_email.Uid=users.Id 
    where users.Id=users_email.Uid limit 0,10 

    foreach($query as $emails) 
    { 
     echo $emails->f_name; 
     echo $emails->Message 
    } 

DB設計產品圖 Link to image

感謝在我的模型的關係

回答

3

有沒有愚蠢的問題。我會盡力給你一個解釋!我不是職業球員,但也許我可以幫忙。 Laravel使用一些非強制性的約定,但如果使用它們,事情就像魅力一樣。 例如,作爲一般性建議,表格應以複數形式命名(您的表格用戶可以,您的「電子郵件」表格應該是「電子郵件」)。該模型應以單數形式命名。這是表格用戶的User.php,表格電子郵件的Email.php。 「數據透視表來源於相關模型名稱的字母順序...」,在本例中爲「email_user」。我再說一遍,您沒有義務像這樣命名它們,因爲您可以指定模型的表格來設置模型中的$ table屬性。 一旦你已經建立了這樣的事情,你只需要添加到您的用戶模式:

public function emails() 
{ 
    return $this->belongsToMany('Email'); 
} 

而在你的電子郵件型號:

public function users() 
{ 
    return $this->belongsToMany('User'); 
} 

之間的「用戶」和「電子郵件」圓括號是相關模型的名稱。

就是這樣。你現在可以這樣做:

$user = User::find(1); 
foreach($user->emails as $email) { 
    echo $email->subject . '<br>'; 
    echo $email->message . '<br>'; 
} 

如果你決定不遵循約定,你仍然可以使用Eloquent關係。你必須建立這樣的關係:

public function nameOfRelation() 
{ 
    return $this->belongsToMany('NameOfRelatedModel', 'name_of_table', 'foreign_key', 'other_key'); 
} 

用戶模型中的例子中:

public function emails() 
    { 
     return $this->belongsToMany('Email', 'users_email', 'Uid', 'email_id'); 
    } 

,並在電子郵件的模式,另一種方式圓。 答案很長!我沒有測試代碼,但這應該給你一個想法! 你可以隨時查看官方的Laravel文檔,這真的很有幫助! http://laravel.com/docs/4.2/eloquent

希望我幫助

+0

由於我與主鍵掙扎這麼感謝的捆綁。 – asim 2015-02-12 08:13:02