CakePHP return find ('all') using 'id' as Index array

So, I'm trying to return an array "all" using the "Product" id as the keyword for each product.

Usually returns:

array(
    (int) 0 => array(
        'Product' => array(
            'id' => '1232',
            'category_id' => '330',
            'name' => 'Product #1',
        )
    ),
    (int) 1 => array(
        'Product' => array(
            'id' => '1245',
            'category_id' => '310',
            'name' => 'Product #2',
        )
    ),
    (int) 2 => array(
        'Product' => array(
            'id' => '1248',
            'category_id' => '312',
            'name' => 'Product #3',
        )
    )
)

      

Ideally I would like it to return:

array(
    (int) 1232 => array(
        'Product' => array(
            'id' => '1232',
            'category_id' => '330',
            'name' => 'Product #1',
        )
    ),
    (int) 1245 => array(
        'Product' => array(
            'id' => '1245',
            'category_id' => '310',
            'name' => 'Product #2',
        )
    ),
    (int) 1248 => array(
        'Product' => array(
            'id' => '1248',
            'category_id' => '312',
            'name' => 'Product #3',
        )
    )
)

      

Is it possible? How can I do it?

I have an Excel spreadsheet that I need to map to IDs, so currently I have to iterate through each row of the table and do the "first" find to get any results, then act on them if they do.

This works, but the set of records has grown to over 28,000, and so doing one find for each has a noticeable overhead.

If I can do this simply in a Find operation, it would be great, if it weren't, a noticeable performance increase would be appreciated.

+3


source to share


2 answers


You can get this result like after searching:

$result = Hash::combine($data, '{n}.Product.id', '{n}.Product');

      



Where $ data is the search result for all.

+6


source


You can use find method in AppModel like this

public function find($type = 'first', $query = array()) {
    switch($type) {
        case 'keysid':

            if($results = parent::find('all', $query)){

                if(isset($results[0][$this->alias]['id'])){

                    return Hash::combine($results, '{n}.'.$this->alias.'.id', '{n}');
                }else{
                    return $results;
                }

            } 
        break;
        default:
            return parent::find($type, $query);
            break;
    }
}

      

And after that, you can call your search method like this:

$this->Product->find('keysid');

      



Then you will have an array of results as you indicated. However, you can also do it with one line of code if you need it once. Say $ products is your array from find ('all')

if($products = $this->Product->find('all')){
        $alteredProducts = Hash::combine($products, '{n}.Product.id', '{n}');
    }

      

Look at Hash

+5


source







All Articles