1

I have this QueryService function:

public static function findAllOrderStatus(): Collection
{
    $orders = TableRegistry::get('b2c_orders');
    $query = $orders->find();

    return $query->select([
        'shop_code' => 'm.mall_code',
        'order_id' => 'b2c_order_number',
        'ship_status' => 'status',
    ])
        ->join([
            'table' => 'malls',
            'alias' => 'm',
            'type' => 'INNER',
            'conditions' => 'b2c_orders.mall_uuid = m.mall_uuid',
        ])
        ->where([
            'm.mall_code' => MALL_ALPEN_OWN
        ])
        ->all();
}

I am getting an error of

Exception: Return value of findAllOrderStatus() must be an instance of Cake\Collection\Collection, instance of Cake\ORM\ResultSet returned

How can I make the $query->select to be a Collection?

andil01
  • 377
  • 4
  • 19

2 Answers2

1

If you want instance of Cake\ORM\ResultSet, you can do other way round. Why don't you use the following way ?

 $iteratorObject = $orders->find() 
     ->join([
        'table' => 'malls',
        'alias' => 'm',
        'type' => 'INNER',
        'conditions' => 'b2c_orders.mall_uuid = m.mall_uuid',
    ])
    ->where([
        'm.mall_code' => MALL_ALPEN_OWN
    ]); 

If you want to use all() and toList(), find it Selecting Rows From A Table

I don't think, select can convert directly to collection object. But, you can do other hacking way to do achieve your goal. You can type cast the Array as an Object when returning it. Something like

(object) $array;

If you want to do that, remove all() and type cast and return it.

If your array is multi-dimensional array, I found it this way in Richard Castera

function arrayToObject($array) {
    if (!is_array($array)) return $array;

    $object = new stdClass();
    if (is_array($array) && count($array) > 0) {
        foreach ($array as $name=>$value) {
            $name = strtolower(trim($name));
            if (!empty($name)) $object->$name = arrayToObject($value);
        }
        return $object;
     }else {
        return false;
     }
}

Hope this help

502_Geek
  • 2,046
  • 2
  • 22
  • 32
1

In case that method resides in a table class, you should rethink its name, as table class methods that start with find can be used as finders, and finders must return query objects.

That being said, if you really want the method to expose a collection compatible return value, then declare the return type as \Cake\Collection\CollectionInterface instead, \Cake\ORM\ResultSet is an indirect implementer via \Cake\Datasource\ResultSetInterface.

See also API > \Cake\Collection\CollectionInterface

ndm
  • 59,784
  • 9
  • 71
  • 110