with() 关系与条件检索所有记录 - 拉拉维尔



我只想检索列出的组织,但数据库返回所有记录。

您可以在下面看到记录不应作为列出的组织返回,我在代码和我的模型和我从数据库中得到的结果

$organisations = Organisation::with(['year_status' => function ($query) use ($year_id) {
$query->where(['year_id' => $year_id, 'is_listed' => 1]);
}])->get();

public function year_status()
{
return $this->hasMany('AppOrganisationYearStatus');
} 
and what I got :
11 => Organisation {#630 ▼
#fillable: array:8 [▶]
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:14 [▼
"id" => 39
"organisation" => "Test Organisation"
"sector_id" => 1
"country_id" => 1
]
#original: array:14 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [▼
"year_status" => Collection {#632 ▼
#items: []
}
]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}

数据库结构 :

id  
organisation_id
year_id
is_listed

确保您的关系已建立(组织模型有许多year_status(,并且您的字段位于 YearStatus 模型的可见数组中。

此外,您正在使用的查询将转换为:

SELECT * FROM organizations where exists 
(select * from year_status where organizaton_id = organizations.id 
and year_id = $year_id and is_listed = 1)

它不会获取数据库中存在的所有记录,而是由于关系+您添加的字段而获取

注意:如果您只想获取具有 OrganizationYearStatus 的组织,则应使用:

Organisation::whenHas('year_status' => function ($advancedWhenHas) use ($year_id) { 
$advancedWhenHas->with(['year_status' => function ($query) use ($year_id) {
$query->where(['year_id' => $year_id, 'is_listed' => 1]);
}}])->get();

您可以键入->toSql()而不是->get(),以确保您的查询是您所期望的查询

最新更新