【问题标题】:How to find a model using pivot table data in Laravel?如何在 Laravel 中使用数据透视表数据查找模型?
【发布时间】:2019-08-23 23:44:53
【问题描述】:

我有一个锦标赛和一个俱乐部模型。我在它们之间使用多对多关系。现在我想使用数据透视表找到一个俱乐部模型。

我试过这个:

$tournament = Tournament::find(1);
    $club = $tournament->clubs->wherePivot('team_as_1','1');
    return $club;

但它显示:Method Illuminate\Database\Eloquent\Collection::wherePivot 不存在。

我的锦标赛模型:

public function clubs(){
        return $this->belongsToMany('App\Club','tbl_club_tournament')->withPivot('team_as_1','team_as_4','team_as_5','team_as_6');
    }

我的俱乐部模型:

public function tournament(){
        return $this->belongsToMany('App\Tournament','tbl_club_tournament')->withPivot('team_as_1','team_as_4','team_as_5','team_as_6');
    }

我想找到一个 team_as_1 = 1 的俱乐部。

【问题讨论】:

    标签: laravel pivot


    【解决方案1】:

    尝试做

    $tournament = Tournament::find(1);
        $club = $tournament->clubs()->wherePivot('team_as_1','1')->get();
        return $club;
    

    使用当前方法,您在集合上调用 wherePivot 方法(但该方法在集合类中不存在),但是通过调用函数 $tournament->clubs(),它返回一个查询构建器对象你可以调用 wherePivot()

    编辑: 似乎你只需要一件物品,所以你应该这样做

    $club = $tournament->clubs()->wherePivot('team_as_1','1')->first();
    

    【讨论】:

    • 它不起作用..它说:Illuminate\Database\Eloquent\Relations\BelongsToMany 无法转换为字符串
    【解决方案2】:

    在下面使用

    $tournament = Tournament::find(1);
    $clubs = $tournament->clubs()->wherePivot('team_as_1','1')->get();
    return $clubs;
    

    【讨论】:

      【解决方案3】:
      return $this->hasManyThrough('App\Club', 'App\Tournament');
      

      【讨论】:

        猜你喜欢
        • 2014-04-20
        • 2014-01-12
        • 1970-01-01
        • 1970-01-01
        • 2017-05-04
        • 1970-01-01
        • 1970-01-01
        • 2020-08-09
        • 1970-01-01
        相关资源
        最近更新 更多