雄辩的嵌套过滤

时间:2014-07-27 00:58:07

标签: laravel orm eloquent relationship

我有一个像这样建模的数据库:

User
+ id
+ email
+ password 

Profile
+ id
+ owner_id (FK user.id)
+ type_id (FK types.id)
+ address_id (FK addresses.id)
+ org_name
+ phone
+ email
+ url
  etc

Postings
+ id
+ profile_id (FK profiles.id)
+ title
+ description

Addresses
+ id
+ street
+ city 
+ province_id (FK provinces.id)
+ country_id (FK countries.id)
  etc

Countries
+ id
+ name

Provinces
+ id
+ name
+ abbreviation
+ country_id

我正在尝试使用Eloquent ORM根据type_id,city,country_id和/或province_id查询一组Postings。这些字段位于从属对象$ posts-> profile->地址等

我是否不得不愚弄我的数据库 - 通过将地址数据合并到其中来平整配置文件?或者有没有办法在Eloquent中执行此操作而不重新构建我的所有数据?

2 个答案:

答案 0 :(得分:0)

假设您为address定义了profile的关系,

$posts = Posting::with([
    'profile' => function($query) use ($type_id)
    {
        $query->whereTypeId($type_id)
    },
    'profile.address' => function($query) use ($country_id, $province_id)
    {
        $query->whereCountryId($country_id)
              ->whereProvinceId($province_id);
    }
])->get();

答案 1 :(得分:0)

这是根据相关表中的约束过滤表的方法:

// we need to pass all the ids to the closure, so use one array for convenience:
$filters = [
    'typeId'     => 1,
    'addressId'  => 5,
    'provinceId' => 10,
    'countryId'  => 15
];

$posts = Posting::whereHas('profile', function ($q) use ($filters) {
  $q->where('type_id', $filters['typeId'])
    ->whereHas('address', function ($q) use ($filters) {
      $q->where('id', $filters['addressId'])

        // both below wheres don't make sense used together, just an example
        ->where('province_id', $filters['provinceId'])
        ->where('country_id', $filters['countryId']);
    });
});

它将设置2个连接并检查那些where子句,因此您将只获取满足要求的那些帖子,但这里没有任何热切的加载(with用于急切加载,但它不过滤主模型,只过滤那些急切的。)