Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
How to use ORM or aggregate
  • Table:
    DROP TABLE IF EXISTS `cars_labels`;
    CREATE TABLE `cars_labels` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(255) DEFAULT '' COMMENT '名称',
      `created_at` int(11) DEFAULT 0 COMMENT '创建时间戳',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB CHARSET=utf8 COMMENT '汽车标签';

    DROP TABLE IF EXISTS `cars_labels_logs`;
    CREATE TABLE `cars_labels_logs` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `label_id` int(11) DEFAULT 0 COMMENT '标签id',
      `car_id` int(11) DEFAULT 0 COMMENT '汽车id',
      `parent_id` int(11) DEFAULT 0 COMMENT '用户id',
      `created_at` int(11) DEFAULT 0 COMMENT '创建时间戳',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB CHARSET=utf8 COMMENT '标签-汽车-用户';

    There is my sql : 
    SELECT t1.*,count(*) as num from cars_labels as t1 LEFT JOIN cars_labels_logs as t2 ON t2.label_id = t1.id GROUP BY t1.id ORDER BY `num` desc;

    so,I want to use orm to get data,but I don't know to do;
  • Harro VertonHarro Verton
    Accepted Answer
    Something like:

    class Model_Carlabels extends \Orm\Model
    {
        protected static $_table_name = 'cars_labels';

        protected static $_belongs_to = array(
            'logs' => array(
                'model_to' => 'Model_Carlabellogs',
                'key_from' => 'id',
                'key_to' => 'label_id',
            ),
        );

    class Model_Carlabellogs extends \Orm\Model
    {
        protected static $_table_name = 'cars_labels_logs';

        protected static $_belongs_to = array(
            'labels' => array(
                'model_to' => 'Model_Carlabels',
                'key_from' => 'label_id',
                'key_to' => 'id',
            ),
        );
    }

    $result = Model_Carlabels::query()->select('*', array(DB::expr("count(*)"), 'num'))
        ->related('logs')
        ->group_by('id')
        ->order_by('num', 'desc')
        ->get();

    // disclaimer: from memory, untested!

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion