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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top