【问题标题】:Laravel many-to-many query with three keys?带有三个键的 Laravel 多对多查询?
【发布时间】:2015-02-11 12:01:25
【问题描述】:

我无法完全理解 laravel 关系系统。我想获得在某个节日在某个乐队演奏的人的变量。

这是我的桌子:

乐队结构表:

id, festival_id, band_id, person_id

人员表:

id, firstname, lastname

节日餐桌:

id, festivalname

乐队表:

id, bandname

在我的节日模型中,我有这个:

    public function persons() {
    return $this->belongsToMany('Person','fs_festival_persons','festival_id','person_id');
}

要列出节日中的所有人,我在控制器中使用以下代码:

$persons = $festival->persons()->get();

而且效果很好。 (从个人节日数据透视表中检索)。但是我不确定如何做一些 laravel 魔术来制作从 Bandstructure 派生的人员列表,当我有festival_id 和 band_id 时,我会在其中检索所有 person_id,并将其放入人员数组中。有任何想法吗?我已经尝试了很多并在 Google 上搜索,但找不到任何适合我的示例。

【问题讨论】:

  • 我可以手动进行如下查询: $persons = DB::table('fs_persons') ->join('fs_bandstruktur', 'person_id','=','fs_persons.id' ) ->where('band_id', '=', $band_id) ->get();这得到了我想要的结果,但希望有一些 laravel 魔法
  • 你试过雄辩的方法“wherePivot()”吗?

标签: php laravel relationship


【解决方案1】:

也许你可以试试wherePivot()这样的雄辩函数:

在您的乐队结构模型中:

<?php
class Bandstruckture extends Eloquent {

    public function persons()
    {
        return $this->belongsToMany('Person')->withPivot(['festival_id', 'band_id']);
    }

}

并像这样使用:

$persons = $festival->persons()->wherePivot('festival_id', $festival_id)->wherePivot('band_id', $band_id)->get();

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 2017-09-30
    • 2018-06-07
    • 1970-01-01
    • 2017-09-11
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多