Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 多对多关系中的Laravel查询生成器 让我们考虑一个名为 Stuttman 的模型,另一个代码运动/通过 PIVOT 表链接:多对多< /强>关系> _Php_Sql_Laravel_Laravel 5_Eloquent - Fatal编程技术网

Php 多对多关系中的Laravel查询生成器 让我们考虑一个名为 Stuttman 的模型,另一个代码运动/通过 PIVOT 表链接:多对多< /强>关系>

Php 多对多关系中的Laravel查询生成器 让我们考虑一个名为 Stuttman 的模型,另一个代码运动/通过 PIVOT 表链接:多对多< /强>关系> ,php,sql,laravel,laravel-5,eloquent,Php,Sql,Laravel,Laravel 5,Eloquent,他们迁移的示例代码 # Sportmans migration Schema::create('sportsmans', function (Blueprint $table) { $table->increments('id'); $table->string('firstname'); $table->string('lastname'); }); # Sports migration Schema::create('sports', functi

他们迁移的示例代码

# Sportmans migration
Schema::create('sportsmans', function (Blueprint $table) {
    $table->increments('id');
    $table->string('firstname');
    $table->string('lastname');
});

# Sports migration
Schema::create('sports', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('description');
});
以下是它们在模型中的关系:

# Defining association in Sportsman model
public function sports(){
    return $this->belongsToMany( Sport::class, 'sportsman_has_sports', 'person_id', 'sport_id' );
}

# Defining association in Sports model
public function sportsman(){
    return $this->belongsToMany( Sportsman::class );
}
我怎样才能用Laravel和雄辩的球技获得那场比赛的
sportsman

  • 只有“足球”
  • 盒子还是“游泳”
  • 网球和篮球
  • 以下是我试图为问题2所做的:

    Sportsman::with(['sports:person_id,id,name'->whereHas('sports', function ($query) {
        $query->whereIn('name', ['Box', 'Swimming'] );
    });
    

    最难的是问题3,你在其中放置了一个子查询,其中有函数

    Sportsman::whereHas('sports', function ($query) {
        $query->whereIn('name', ['Box', 'Swimming'] );
    })
    ->with('sports')
    ->get();
    // Below is your last question
    Sportsman::where(function ($query) {
        $query->whereHas('sports', function ($subquery) {
            $subquery->where('name', 'Tennis');
        });
        $query->whereHas('sports', function ($subquery) {
            $subquery->where('name', 'Basket-ball');
        });
    })
    ->with('sports')
    ->get();
    

    到目前为止,你尝试了什么?这篇文章是用我的方法编辑的,以回答你的问题。你的方法对问题2不起作用的是什么?什么是“网球和篮球”意思?这是有效的,但正如我所说,对问题3来说更难。我想的是去做(问题3)在调用
    get
    method后,按程序进行设置。当您已经有了解决方案时,为什么还要问这个问题?网球和篮球是什么“是吗?它可以工作,但问题是它将执行更复杂/庞大的查询,因为对于请求中存在的每个运动,它将添加一个额外的连接。所以,您不认为在基本查询执行之后过滤结果(作为简单的集合)会更好吗?我不建议您这样做,因为随着时间的推移,数据会增长,并且您会将不必要的数据带到集合中,这会减慢您的应用程序。