【问题标题】:Select only related entries for the model in Laravel在 Laravel 中仅选择模型的相关条目
【发布时间】:2016-05-22 07:43:38
【问题描述】:

我完全陷入了如何从模型(匹配)中仅获取两个相关条目(团队)的问题。

问题:

以下代码得到正确匹配,但所有现有团队也是如此。一场比赛只有 两支 队互相比赛,而这两支球队我都无法明确表示:-)

Match::with('teams')
    ->whereBetween('elo', [($request->user()->elo - 100), ($request->user()->elo + 100)])
    ->where('winner_id', 0)
    ->where('type', 'normal')
    ->get();

目标:

我想让这两支球队在比赛和球队建立之后,将一名球员分配给两支球队中的一支。但是如果我的观点是正确的,那么仅仅选择最后两个条目是不够的!

  1. 创建匹配(检查)
  2. 创建 2 个团队(检查)
  3. 将球员分配到其中一支球队(卡住)

表格:

匹配项(id、winner_id、...)
团队(id、ma​​tch_id、...)
玩家(id、user_id、team_id、...)

关系:

class Match extends Model
{
    protected $table = 'matches';

    public function teams()
    {
        return $this->hasMany(Team::class);
    }

    public function winner()
    {
        return $this->belongsTo(Team::class, 'winner_id');
    }
}

你能告诉我这需要什么吗?

【问题讨论】:

  • 请用代码说明问题出在哪里。你的关系有问题吗?
  • 我在用雄辩的语言指出正确的查询以将两支球队分配到一场比赛时遇到问题。
  • 好的,那么两个团队的标准是什么?
  • 我的意思是你是根据什么选择两个团队的?
  • 只需添加 where('match_id',YOUR_VALUE_HERE) 即可获得团队,有什么问题

标签: laravel laravel-5 eloquent query-builder laravel-5.2


【解决方案1】:

根据您在这篇文章的 cmets 中告诉我的内容,一场比赛将有多名球员和多支球队 (2) 并且球员和球队都为/属于一场比赛。考虑到这一点,您正在查看一组相当简单的关系/

匹配模型

class Match extends Model {
    protected $table = 'matches';

    public function teams()
    {
        return $this->hasMany(Team::class);
     }

    public function winner()
    {
        return $this->belongsTo(Team::class, 'winner_id');
    }
}

团队模型

class Team extends Model {
    protected $table = 'teams';

    public function match()
    {
        return $this->belongsTo(Match::class);
    }

    public function players()
    {
        return $this->hasMany(Player::class);
    }
}

玩家模型

class Player extends Model {
    protected $table = 'players';

    public function team()
    {
        return $this->belongsTo(Team::class);
     }
}

现在要将一名球员分配给其中一支球队(以及比赛),您必须使用associate 方法。你如何做取决于你开始使用什么数据。如果您已经了解该团队,您可以这样做:

$team = Team::find(123);
$player = Player::find(8734); //could also have created new Player here

$team->players()->associate($player);

如果你不了解球队,但只知道比赛,你可以这样做:

$match = Match::with('teams')->find(9003);
$team = $match->teams[0]; //choose teams[1] for second team, etc.
$player = Player::find(8734); //could also have created new Player here

$team->players()->associate($player);

您始终可以通过以下方式获取所有相关数据:

Match::with('teams.players')->find(9003);

这将返回比赛数据以及参加该特定比赛的球队和属于该球队的球员。

【讨论】:

  • 您好,先生。我忘了解释这些“球队”不像足球队。每支球队将永远是一组 5 名球员,分数相同。所以 1 支球队只会参加 1 场比赛。这会影响您上次的数据查询吗?因为它看起来很漂亮,而不是我的:-)
  • 所以你是说一支球队只参加一场比赛?那么一个球员可以同时属于多个球队吗?
  • 没有。它真的更像是一个每次都可以改变的瑜伽小组:D 你知道玩家在团队中匹配的“moba 游戏”吗?
  • 但是一名球员可以参加不止一场比赛,对吧?还是每场比赛只有一名球员和一支球队只有,而且每场比赛都是全新的?在我修改我的答案之前,只需要完全弄清楚这些关系。
  • 每一场比赛都是全新的。
猜你喜欢
  • 2014-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-07
  • 2017-03-12
  • 1970-01-01
  • 2018-11-11
  • 1970-01-01
相关资源
最近更新 更多