【问题标题】:How can I access model Relation with where condition of child and parent table in laravel?如何使用 laravel 中子表和父表的 where 条件访问模型关系?
【发布时间】:2020-04-24 16:49:31
【问题描述】:

我有 Games 表,它具有以下架构

标识 |状态 |名字

status 列有 2 个值(Active、Pending)

以及具有以下架构的 GamePlayer 表

标识 |游戏ID | player_id |请求状态

request_status 列有 3 个值(Pending、Confirm、Rejected)

现在我必须选择玩家参与的所有游戏,但有以下限制:

如果游戏处于 Pending 状态,那么它将显示给所有 game_players 如果游戏处于 Active 状态,那么它只会显示给 request_status 为 Confirm 的 game_player。 游戏(模型)

public function GamePlayer()
{
        return $this->hasMany('App\Models\GamePlayer', 'game_id', 'id');
}


public function getGames($playerId)
{
        $gameList = Game::with(['GamePlayer','Category:id,name'])
         ->whereHas('GamePlayer', function ($q) use ($playerId) {
                      $q->where('player_id', $playerId);
         })->get();
        return $gameList;
}

控制器

$this->gameObj = new Game();
$gameList = $this->gameObj->getGames($player_id);

请帮助我如何根据条件(父表和子表)填充另一个表中的数据。

【问题讨论】:

  • 你的意思是像join()这样的方法吗?
  • 是的,但如果可能的话使用雄辩的关系

标签: laravel eloquent orm


【解决方案1】:

您可以在您的关系中使用条件来仅获得确认的游戏玩家

    public function activeGamePlayers()
    {
        return $this->hasMany('App\Models\GamePlayer', 'game_id', 'id')
            ->where('request_status', 'confirm');
    }

您也可以使用范围 (https://laravel.com/docs/7.x/eloquent#local-scopes) 仅选择活动游戏

    public function scopeActive($query)
    {
        return $query->where('status', 'active');
        // You can then use $game->active()->...
    }

所以你的getGame 看起来像:

   public function getGames($playerId)
    {
        $player = GamePlayer::find($playerId);
        if ($player->status == 'active') {
            $gameList = Game::with(['GamePlayer', 'Category:id,name'])
                ->get();
        } else {
            $gameList = Game::with(['GamePlayer', 'Category:id,name'])
                ->active()->get();
        }
        return $gameList;
    }

注意:

在您的具体情况下,我会改为从 GamePlayer 模型开始获取游戏,而不是从游戏模型开始 - 您也可以在关系中使用范围和条件,以使您的代码更具可读性。

【讨论】:

    【解决方案2】:

    你可以使用 Laravel 方法whereHas。你应该阅读 Laravel 文档的 this 部分。 请注意,您应该在每个模型上声明关系。

    【讨论】:

      猜你喜欢
      • 2013-09-02
      • 2019-05-30
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-15
      • 2013-01-15
      • 2016-06-20
      相关资源
      最近更新 更多