【问题标题】:Get data from three models with relationship laravel使用关系 laravel 从三个模型中获取数据
【发布时间】:2020-04-30 18:54:40
【问题描述】:

我有三个模型:

系列($id)

public function saisons() 
{
    return $this->hasMany(Season::class);
}

public function episodes() 
{
    return $this->hasManyThrough(Episode::class, Season::class);
}

赛季 ($serie_id)

public function serie()
{
    return $this->belongsTo(Serie::class);
}

public function episodes() 
{
    return $this->hasMany(Episode::class);
}

剧集($season_id)

public function season()
{
    return $this->belongsTo(Season::class);
}

public function serie()
{
    return $this->BelongsToThrough(Serie::class, Season::class);
}

我想展示一个系列中的一个特定季节以及相关的剧集

我的看法

<h1 class="title">{{$serie->seasons->number}}</h1>


@foreach ($serie->seasons->episodes as $episode)

        <div class="row">
            <div class="columns">
                <div class="col">
       {{$episode->number}}
       <a href="{{route('episodes.show', $episode->id)}}">{{$episode->name}}</a>



        @if(isset($episode->programmation->date))

            {{$episode->programmation->date}}

        @endif
       @if (($episode->season_finale) == '0')
            Non
            @elseif (($episode->season_finale) == '1')
            Oui
            @endif

        @foreach ($episode->chaines as $chaine)
                   {{$chaine->name}}

            @endforeach
        </div>
        </div>
    </div>
    @endforeach

路线

Route::get('/serie/{serie}/saison/{season}', 'Front\SaisonController@show')->name('saison.show');

对于我的 url,我选择显示 saison 的编号而不是 id,我认为这就是问题所在。

我怎样才能以正确的方式做到这一点?

【问题讨论】:

  • 你不需要赛季连接到意甲。你只是插曲季节逻辑。您将在剧集中获得系列的剧集。这会更简单。
  • 好的,但是我如何才能在我的视野中获得正确的季节?
  • 我说的是数据库逻辑。可能的好方法是在episodes 表中有season 列,因为它是剧集实体的关键部分。但是,如果您需要使用第三季表,例如this。再次尝试添加episodes.season 字段并仅使用SerieEpisode 模型。
  • 我试过这个,它给了我这个错误: SQLSTATE [23000]:完整性约束违规:1052 where 子句中的列 'id' 不明确(SQL:select * from episodes where exists (select * 从serie 内部连接seasonseason.serie_id = serie.id 其中season.id = episodes.season_id 和 (@187654344@) ) 并且存在 (select * from season where episodes.season_id = season.id 和 (season = 2))) 我对 Laravel 和 php 比较陌生,而且它非常对我来说很复杂,即使有你的解释我也不知道该怎么做:(
  • 好的,谢谢你的帮助!

标签: laravel eloquent-relationship


【解决方案1】:

我认为这种方法可以帮助你。

$serie = Serie::where('id',$id)->with('seasons'=>function($query) use ($season_id) {
            $query->where('season_id',$season_id)->with('episodes')->get();
    })->get();

【讨论】:

  • 我有一个错误:尝试获取非对象的属性“编号”
【解决方案2】:

好的,有人帮我找到正确的答案:

     $serie = Serie::findOrFail($serie);
     $season =  Season::where('serie_id', $serie->id)->where('season.number', $season)->first();

【讨论】:

    猜你喜欢
    • 2019-09-12
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-09
    • 2016-08-20
    相关资源
    最近更新 更多