我有这个方法用于根据搜索查询过滤结果集。正如您所看到的,它将从模型中获取Fillable
元素并搜索那些元素(可能效率不高,但它可以工作且非常快)。
public static function searchAgainstFillable(&$query, $options, $useRelations = null){
// Get a list of fillable fields from the model
if($query->first() != null){
if(!$useRelations){
$fillables = $query->first()->getFillable();
// We could throw an exception here - but just in case oddities have occurred its
// probably best to just ignore an empty search term.
if(isset($options['search'])){
$results = $query->filter(function($setting) use($options, $query, $fillables){
foreach($fillables as $field){
if(stripos($setting->{$field}, $options['search']) !== false){
return true;
}
}
});
}
// Finally we want to overwrite the results passed in with the newly
// filtered results, ready to be presented in the response
$query = $results;
}
}
不幸的是,我发现在使用具有多个层的模型时,此代码只能用于基表而不是任何其他关系。有没有办法可以做到这一点,而不是手动对每个关系层运行foreach
?以下是我的查询摘录。
{
"id": 1,
"created_at": "2015-05-18 15:10:59",
"updated_at": "2015-05-18 15:10:59",
"deleted_at": null,
"response_id": 10,
"user_id": 1,
"assigned_at": null,
"follow_up_step_num": 0,
"is_dropped_out": 0,
"assigned_user": {
"id": 1,
"created_at": "2015-05-15 13:18:22",
"updated_at": "2015-05-15 13:18:22",
"email": "REMOVED",
"firstname": "system",
"lastname": "user",
"location_id": 0,
"deleted_at": null,
"permissions": [],
"location_tags": []
},
"interactions": [
{
"id": 1,
"created_at": "2015-05-18 15:10:59",
"updated_at": "2015-05-18 15:10:59",
"deleted_at": null,
"closed_loop_interaction_type_id": 1,
"interaction_note": "Test Interaction note",
"closed_loop_processes_id": 1,
"interaction_type": {
"id": 1,
"created_at": "2015-05-18 15:10:59",
"updated_at": "2015-05-18 15:10:59",
"deleted_at": null,
"type": 0,
"method": "Phone Call (mobile)"
}
}
],
"response": [
{
"id": 10,
"created_at": "2015-02-20 18:48:07",
"updated_at": "2015-05-18 15:10:58",
"survey_request_id": 9,
"response": "Ullam mollitia explicabo accusamus ipsam ad in corrupti. Sed corrupti fugiat veritatis eaque accusantium non eaque deleniti. Doloremque rerum excepturi et adipisci. Et dicta corrupti omnis.",
"score": 8,
"deleted_at": null,
"survey_requests": null
}
]
}
理想情况下,我希望能够搜索匹配的每个模型以及它们可能包含的任何可填写字段。