Kohana Jelly:如何从 Jelly 集合快速创建数组?
假设你有一个模特。每个 Person 对象可以有许多 Friends (Field_HasMany)。
如果您想获取给定 Person 的朋友的简单名称/ID 对数组,那么像这样获取朋友是否更快/更好:
$friends = $person->friends;
然后使用 foreach 循环从该对象创建一个数组
或
执行选择,如下所示:
$friends = Jelly::select('friend')
->join('people')
->on('person.id','=','friends_people.person_id')
->where('person_id','=',$person->id)
->execute()
->as_array('name', 'id');
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');
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
基本上,Jelly 所做的就是在您请求 $person 的朋友时构建正确的查询(这与您的自定义查询类似)
要在数组中获取朋友,您可以执行与自定义查询完全相同的操作:
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:
问题是其他的......因为一个(注意一个)人可以有很多(很多)朋友
所以关系不是多对多而是一对多:S
其他人认为如果你真的需要多对多关系,你需要第三个表来粘合。
在这种情况下,如果您有一对多关系,“一个人有很多朋友”。
你可以做
Person->friends->findAll() 获取给定人员 ID 的所有朋友:)
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 :)