Closed chrisgo closed 14 years ago
$value = $some_model->has_many_field[$name_of_field]->some_field;
What are you trying to do with this line? That syntax is not something I would expect to work. is 'has_many_field' a relationship alias? If so that is retrieving the Jelly_Collection for the relationship and then trying to access the object as an array. That in itself is valid but it will be 0 indexed so passing a string will get you no where. Since the handling of square brackets is part of PHP's interpreter, there is not a lot we can do if PHP passes keys by reference.
All in all I think that is invalid syntax and it doesn't surprise me that it doesn't work as you want.
Your second example 'works' (as in prints the same string) because you have copied it as you suggest but the line in the middle still won't actually do anything sensible.
What are you trying to achieve with this syntax?
What you said makes sense ... I actually found something that works better.
What I am trying to do is find a specific "named" (I suppose we can use the name_key or one of the meta aliases?) object from the list of HasMany relationships. Perhaps this example (stripped down) would make it clear
get_object_by_name($objects, $name)
{
foreach($objects as $object)
{
if( $object->name == $name )
{
return $object;
}
}
return null;
}
then
$specific_object = get_object_by_name($some_model->has_many_field, $name_of_field);
I was just going to put this in my Model_Base (where all my other models extend from). Is there a better way?
If you know the name and the name is unique why do you need to get it from the model?
Anyway, you could do this as below although it may require an extra query if you are already loading the relations for other purposes. In that case, PHP filtering like you have suggested is probably the best way to go.
$value = $some_model->get('has_many_alias')
->where(':name_key', '=', 'Some Name')
->load(); // load limits to 1 (assuming name key is unique) returns the object directly
I've checked out the latest source (just now) and there seems to be a bug (not exactly sure where) when you pass in a name to get access to a HasMany field.
In the example below, the variable $name_of_field is being reset to 0 (zero)
the way to not have this behavior (after an hour of trying and grabbing the latest sources)
I have to append an empty string to $name_of_field so that the variable doesn't get "trampled" .. possibly an errant pass-by-reference issue?
Thanks, Chris