2016-07-22 91 views
0

我有兩個型號AwardGotAward,GotAward型號有Award型號的外鍵。Laravel:兩張表的記錄

我想從Award模型中獲取所有記錄,然後在GotAward模型中檢查每個Award模型ID,我必須向用戶顯示「您已經獲得這些獎勵」。

我有以下代碼:

$awards = App\Award::all(); 

foreach ($awards as $checkAward) { 
    $unlockedAwards = App\unlockedAward::where('award_id','=',$awards->id); 
} 

這是一個好的做法呢?

回答

1
<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class GotAward extends Model 
{ 

    public function award(){ 
     return $this->hasOne('App\Award'); 
     //You can also specify the relationship in case of different fields in the DB table. By convention Laravel will check award_id in gotawards table 
/* return $this->hasOne('App\Award', 'award_id', 'gotaward_id');*/ 

    } 


} 

您查詢GotAward模型後後。

$result = $GotAward::where('condtion', 'value')->first(); 

$result->award->award_column_to_shwo_to_user將包含來自awards表的數據。

看看口才關係,here.

+0

我也想在'awards'表我的意思'Award'模型中的所有記錄。 我必須向用戶展示所有獎項,並且在獎項頒發之前,如果他/她沒有獎勵,將會有勾號或交叉符號。 我該怎麼做? – Gammer

0

沒有 請看relationships

在你的獎型號指定的hasMany你可以做財產以後像 $award->AllAwards()