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

1.1k views Asked by At

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');
2

There are 2 answers

0
SpadXIII On BEST ANSWER

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');
2
Czuma On

the problem is other... because one (note ONE) person can have many (MANY) Friends so the relationship is not many to many is One to Many :S other think if you really need many to many relationship you need a third table to glue. in this case if you have a one to many relationship "a person have many friends". you can do Person->friends->findAll() to fetch all friends of a given person ID :)