Laravel:两张表的记录

Laravel:两张表的记录

问题描述:

我有两个型号AwardGotAward,GotAward型号有Award型号的外键。Laravel:两张表的记录

我想从Award模型中获取所有记录,然后在GotAward模型中检查每个Award模型ID,我必须向用户显示“您已经获得这些奖励”。

我有以下代码:

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

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

这是一个好的做法呢?

<?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

没有 请看relationships

在你的奖型号指定的hasMany你可以做财产以后像 $award->AllAwards()