雄辩的过滤嵌套 [英] Eloquent filtering of nested
问题描述
用户
+ id
+电子邮件
+密码
个人资料
+ id
+ owner_id(FK user.id)
+ type_id(FK types.id)
+ address_id FK addresses.id)
+ org_name
+手机
+电子邮件
+ url
etc
发布
+ id
+ profile_id(FK profiles.id)
+ title
+ description
地址
+ id
+ street
+ city
+ province_id(FK countries.id)
+ country_id(FK countries.id)
etc
国家
+ id
+名称
省份
+ id
+名称
+缩写
+ country_id
我正在尝试使用Eloquent ORM根据type_id,city,country_id和/或province_id来查询一组过帐。这些字段位于从属对象$ posting-> profile-> address等。
我将不得不贬低我的数据库 - 将地址数据合并到其中?或者有没有办法在口才这样做,而不重写所有的数据?
这是你如何过滤表相关表中的约束:
//我们需要将所有ids传递给闭包,因此为方便起见使用一个数组:
$ 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' )
//两个下面都没有意义一起使用,只是一个例子
- > where('province_id',$ filters ['provinceId'])
- > where('country_id',$ filters ['countryId']);
});
});
它将设置2个连接并检查那些其中
子句,所以你只能获取满足要求的那些帖子,但没有什么是渴望加载的(与
是为了加载,但它不会过滤主模型,只有那些渴望加载)。
I have a db modelled like this:
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
I am trying to use Eloquent ORM to query a set of Postings from this based upon type_id, city, country_id and/or province_id. These fields are on the subordinate object $posting->profile->address, etc.
Am I going to have to dumb-down my db - flatten out the profile by merging the address data into it? Or is there a way to do this in Eloquent without remodelling all my data?
This is how you filter the table based on constraints in related tables:
// 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']);
});
});
It will set 2 joins and check those where
clauses, so you will fetch only those posts, that meet the requirements, but nothing is eager loaded here (with
is for eager loading, but it doesn't filter the main model, only those eager loaded).
这篇关于雄辩的过滤嵌套的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!