【问题标题】:Where in pivot tables在数据透视表中的位置
【发布时间】:2018-01-18 09:18:11
【问题描述】:

我有下一个数据透视表:

Schema::create('coach_user', function(Blueprint $table)
        {
            $table->integer('coach_id')->unsigned()->index();
            $table->foreign('coach_id')->references('id')->on('coaches')->onDelete('cascade');
            $table->integer('user_id')->unsigned()->index();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->tinyInteger('rank');
        });

在 User.php 中:

 public function coaches()
    {
        return $this->belongsToMany(\App\Coach::class)->withPivot('rank');
    }

我怎样才能接收一些等级的用户教练?像这样:

$user->coaches->where('rank',1)->get().

【问题讨论】:

    标签: php laravel pivot where-clause


    【解决方案1】:

    使用wherePivot()filterbelongsToMany返回的结果。

    $user->coaches()->wherePivot('rank',1)->get();
    

    【讨论】:

    • 不工作。但接下来工作:$user->coaches()->wherePivot('rank',1)->get()。你知道为什么吗?
    【解决方案2】:

    使用wherePivot 作为透视列和关系作为方法:

    $user->coaches()->wherePivot('rank',1)->get().
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-30
      • 1970-01-01
      • 2018-10-06
      • 2014-07-11
      • 1970-01-01
      • 1970-01-01
      • 2018-04-10
      相关资源
      最近更新 更多