Laravel 4 - 过滤集合

时间:2014-09-05 14:53:16

标签: php laravel-4 blade

我在变量$types中有以下结果集;我有第二个变量$typeid,目前的值为11

[
    {"_id":"54077696dee5bd6ce0000029","typeID":"2","type":"road"},
    {"_id":"54077696dee5bd6ce000002a","typeID":"3","type":"street"},
    {"_id":"54077696dee5bd6ce000002b","typeID":"4","type":"avenue"},
    {"_id":"54077696dee5bd6ce000002c","typeID":"5","type":"place"},
    {"_id":"54077696dee5bd6ce000002d","typeID":"6","type":"drive"},
    {"_id":"54077696dee5bd6ce000002e","typeID":"7","type":"way"},
    {"_id":"54077696dee5bd6ce000002f","typeID":"8","type":"blvd"},
    {"_id":"54077696dee5bd6ce0000030","typeID":"9","type":"court"},
    {"_id":"54077696dee5bd6ce0000031","typeID":"10","type":"lane"},
    {"_id":"54077696dee5bd6ce0000032","typeID":"11","type":"mile"}
]

我想在不使用type的情况下检索相应的mile@for loop)。我尝试使用以下内容:

{{ 
    $types->filter(function($t) use ($typeid) { 
        return $t->typeID == $typeid; 
    })->type 
}}

但我收到错误:

Undefined property: Illuminate\Database\Eloquent\Collection::$type

因为$types->filter(function($t) use($typeid) { return $t->typeID == $typeid; })返回以下内容(我认为"9"是上面数组中的索引...不能保证记录将保持给定的顺序):

{"9":{"_id":"54077696dee5bd6ce0000032","typeID":"11","type":"mile"}}

我期待{"_id":"54077696dee5bd6ce0000032","typeID":"11","type":"mile"}。有没有办法重写->filter方法,以便它可以返回:

{"_id":"54077696dee5bd6ce0000032","typeID":"11","type":"mile"}
//or
[{"_id":"54077696dee5bd6ce0000032","typeID":"11","type":"mile"}]  //?

或者,有没有办法写行,以便我得到所需的结果:例如以11开头并获得里程。

2 个答案:

答案 0 :(得分:0)

在不知道你如何查询收藏品的情况下,很难说。假设您正在使用名为Type的Eloquent模型。执行此操作的最佳方法是在模型中创建查询范围。

$types = Type::ofTypeId($typeid)->get();

在您的模型中,您将添加以下功能:

public function scopeOfTypeId($query, $typeid)
{
    return $query->whereTypeID($typeid);
}

答案 1 :(得分:0)

文档中有一条注释,直到现在才有意义:

  

注意:过滤集合并将其转换为JSON时,请尝试   首先调用values函数来重置数组的键。

因此,如下重写该行可以解决问题:

{{ 
    $types->filter(function($t) use ($typeid) { 
        return $t->typeID == $typeid; 
    })->values()[0]->type 
}}

由于$types->filter(function($t) use ($typeid) { return $t->typeID == $typeid; })->values()的值为:

[{"_id":"54077696dee5bd6ce0000032","typeID":"11","type":"mile"}]