开发者

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


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


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 :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜