Love Fuel?
Donate
About
Forums
Discussions
Login
FuelPHP Forums
Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Orm
How to use ORM or aggregate
moting
September 2017
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
September 2017
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!
Add a Comment
Howdy, Stranger!
It looks like you're new here. If you want to get involved, click one of these buttons!
Sign In
Apply for Membership
Categories
All Discussions
5,088
General
↳ General
3,364
↳ Job Board
13
↳ Installation & Setup
214
Packages
↳ Oil
213
↳ Orm
700
↳ Auth
260
Development
↳ Tips and Tutorials
126
↳ Code share
145
↳ Applications
52
In this Discussion
Harro
September 2017