Frage

Assume the following association among three tables in a database:

    //working with three tables a client 'has one' business
    //and a business has many business hours.

The following would give us an array of Activerecord objects:

$this->client->business->businesshours

and we would have to pull an object form the array to get its column value:

$this->client->business->businesshours[0]->start_time

Since I am new to PHP Activerecord, what are some ways of proceeding to pull/sort/use information from an array of objects other than looping with a foreach() loop? Are there methods to sort through the array of objects, pull information based on a column value, any best practices?

War es hilfreich?

Lösung

There is not a library-specific practice for sorting or pulling certain businesshour objects out of the result array. If you want to manipulate the returned array of objects you need to use standard PHP array functions like array_map on the result array.

If you know the sort order or the conditions you want for the returned objects in the result array you should instead specify these in your association declaration so you don't return objects that you don't want or need.

Since you haven't posted any code you'll just have to extrapolate to your own situation from this example:

static $has_many = array(
  array(
    'businesshours',
    'conditions' => array('hour BETWEEN ? AND ?' => array(9, 17)),
    'order' => 'hour ASC'
  )
);

This association declaration will return only the businesshour objects between 9 and 17 and do it in ascending order. So as you can see, if you constrain your associations to only the records you need, there will be no need to sort or parse the result array once received.

Sometimes it's useful to use array_map to get only certain objects from your result array:

// get $result array
$new = array_map(function($obj) { if ($obj->hour > 9){ return $obj; } }, $result);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top