如何在laravel中的三个表之间进行连接查询

时间:2017-01-14 08:43:18

标签: laravel query-builder laravel-query-builder

我想在三个表(区域,国家/地区,包)之间的laravel中构建一个查询,以便表格相关。

  1. 区域表包含(id,名称,描述)
  2. 国家/地区表包含(id,region_id,名称,描述)
  3. 包表包含(id,county_id,pkg_title,pkg_description,price)
  4. 我想选择region_id = 1的所有包 如何在laravel查询生成器中查询此情况。请帮我解决这个问题

3 个答案:

答案 0 :(得分:1)

按如下方式设置模型。

class Region extends Model
{

}

class Country extends Model
{
    public function region()
    {
        return $this->belongsTo(Region::class);
    }
}

class Package extends Model
{
    public function country()
    {
       return $this->belongsTo(Country::class);
    }
}

并在您的方法中查询以下查询。

$region_id = 1;
$PackageWithRegions = Package::with([
    'country' => function ($county) use ($region_id) {
        return $county->with([
            'region' => function ($region) use ($region_id) {
                return $region->where('id', $region_id);
            }
        ]);
    }
])->get();
// $PackageWithRegions is a collection of packeges with regions where regiion_id = 1

更多关于eloquent relationships

答案 1 :(得分:0)

您可以使用Eloquent模型关系来执行此操作,如下所示

在区域控制器文件

$region = Region::where(['id'=>1])->with(['country'])->get(); ///fetch region with country calls relation declared in region model

在Region.php模型中

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Region extends Model {

  protected $table = 'regions';


  public function country(){
    return $this->hasOne('App\Models\Country','region_id')->with(['packages']); ///this will fetch country with all pacckages on matching region_id, join of package  with country is declared in country model. 
  }
}

在Country.php模型中

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Country extends Model {

  protected $table = 'countries';

  public function packages(){
    return $this->hasMany('App\Models\Package','county_id'); //join of country with packages on county_id
  }

}

在Package.php模型中

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Package extends Model {

  protected $table = 'packages';

}

答案 2 :(得分:0)

你可以在Laravel doc(https://laravel.com/docs/4.2/eloquent)的“Has Many Through”一节中看到,如果你有一个类似的模型:

interface IDispatchProps {
  fetchEntity: typeof fetchEntity
}

然后您可以通过这种方式访问​​最后一个关系:

countries
    id - integer
    name - string

users
    id - integer
    country_id - integer
    name - string

posts
    id - integer
    user_id - integer
    title - string

或使用海关关系ID:

class Country extends Eloquent {

    public function posts()
    {
        return $this->hasManyThrough('Post', 'User');
    }

}

因此,您可以访问某个国家/地区的帖子:

class Country extends Eloquent {

    public function posts()
    {
        return $this->hasManyThrough('Post', 'User', 'country_id', 'user_id');
    }

}