【问题标题】:Laravel : Records from two tablesLaravel:来自两个表的记录
【发布时间】:2016-11-25 22:32:14
【问题描述】:

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

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

我有以下代码:

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

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

这是一个好习惯吗?

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    没有 请查看relationships

    在您的奖励模型中指定 hasMany 之后,您可以执行类似的操作 $award->AllAwards()

    【讨论】:

      【解决方案2】:

      【讨论】:

        【解决方案3】:
        <?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-&gt;award-&gt;award_column_to_shwo_to_user 将包含来自奖项表的数据。

        看看Eloquent关系,here.

        【讨论】:

        • 我还想要awards 表中的所有记录,我的意思是Award 模型。我必须向用户展示所有奖励,如果他有/没有奖励,在奖励标题之前会有勾号或叉号。我该怎么做?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-15
        • 2019-04-01
        • 1970-01-01
        相关资源
        最近更新 更多