【问题标题】:Laravel query mergingLaravel 查询合并
【发布时间】:2014-06-17 21:10:45
【问题描述】:

我有以下表格:
阶段,赌注,赌注类型。 一个阶段有很多赌注,一个赌注属于一个阶段,一个赌注有很多 bet_type,一个 bet_type 属于很多赌注(多对多)。 我希望能够返回给定阶段的所有赌注和每个赌注的 bet_types(一个赌注由许多 bet_types 组成)。

例如:

Phase table:
id  name  
1   phase1


Bet table:
id  name  phase
1   bet1  1
2   bet2  1


Bet_Type table:
id  name
1   bet_type1
2   bet_type2


Bet_Bet_Type (connection table):
bet_id   bet_type_id
1        1
1        2
2        1

我想得到的结果是:

{
    bets: 
    [
        {
            id: 1,
            name: "bet1",
            bet_type: 
            [
                {
                    id: 1,
                    name: "bet_type1"
                },
                {
                    id: 2,
                    name: "bet_type2"
                }
            ]
        },
        {
            id: 2,
            name: "bet2",
            bet_type: 
            [
                {
                    id: 1,
                    name: "bet_type1"
                }
            ]
        }
    ]
}

我知道如何获得一个阶段的所有赌注,如下所示:

$bets = Phase::find($phaseId)->bets()->get();

但是我怎样才能得到上面的呢?

【问题讨论】:

    标签: php sql laravel relational-database eloquent


    【解决方案1】:

    你可以试试这个:

    $phase = Phase::with('bets.betTypes')->find($phaseId);
    

    这需要声明关系方法:

    // Phase Model
    public function bets()
    {
        return $this->hasMany('Bet');
    }
    
    // Bet Model
    public function betTypes()
    {
        return $this->belongsToMany('BetType');
    }
    
    // BetType Model
    public function bets()
    {
        return $this->belongsToMany('Bet');
    }
    

    所以你可以使用这样的东西:

    $phase = Phase::with('bets.betTypes')->find($phaseId);
    
    // Get all bets
    $bets = $phase->bets;
    
    // Get all betTypes from first Bet
    $betTypes = $phase->bets->first()->betTypes;
    
    // Get all betTypes from second Bet
    $betTypes = $phase->bets->get(1)->betTypes;
    
    // Get first betType from second Bet
    $betType1 = $phase->bets->get(1)->betTypes->get(0); // or first()
    

    如果你在视图中循环(Blade):

    {{ $phase->name }}
    @foreach($phase->bets as $bet)
        {{ $bet->name }}
        @foreach($bet->betTypes as $betType)
            {{ $betType->name }}
        @endforeach
    @endforeach
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-17
      • 1970-01-01
      • 1970-01-01
      • 2019-01-24
      • 2016-09-28
      • 2021-02-23
      • 1970-01-01
      • 2020-12-06
      相关资源
      最近更新 更多