Laravel:两张桌子的记录

时间:2016-07-22 06:13:24

标签: php laravel

我有两个模型AwardGotAwardGotAward模型具有Award模型的外键。

我想从Award模型中获取所有记录,然后检查Award模型中的每个GotAward模型ID,我必须向用户显示"您有这些奖项"。

我有以下代码:

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

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

这是一个好习惯吗?

3 个答案:

答案 0 :(得分: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将包含奖励表中的数据。

看一下Eloquent关系,here.

答案 1 :(得分:0)

没有 请查看relationships

在您的奖励模型中指定hasMany后,您可以做类似的事情 $award->AllAwards()

答案 2 :(得分:0)

相关问题