Search code examples
arrayscollectionskohanajelly

Kohana Jelly: how to quickly create an array from a Jelly collection?


Say you have a model Person. Each Person object can have many Friends (Field_HasMany).

If you want to get a simple array of name/id pairs for a given Person's friends, is it faster/better to get the Friends like so:

$friends = $person->friends;

and then create an array from that object with a foreach loop

OR

do a select, like so:

$friends = Jelly::select('friend')
->join('people')
->on('person.id','=','friends_people.person_id')
->where('person_id','=',$person->id)
->execute()  
->as_array('name', 'id');

Solution

  • Basically what Jelly does is build the correct query when you request a $person's friends (which is similar to your custom query)

    To get friends in an array, you can do exactly the same thing as you're doing with your custom query:

    $friends = $person->friends->as_array('id', 'name');