0

我有三张桌子,

作品:

CREATE TABLE `works` (
  `work_id` int(11) NOT NULL AUTO_INCREMENT,
  `project_id` int(11) NOT NULL,
  `work_name` varchar(100) NOT NULL,
  `work_baslangic` int(11) NOT NULL,
  `work_bitis` int(11) NOT NULL,
  `work_onay` enum('0','1') NOT NULL,
  `work_onay_userid` int(11) NOT NULL,
  `work_brief` text NOT NULL,
  `work_not` text NOT NULL,
  `work_url` varchar(50) NOT NULL,
  `work_employees` varchar(200) NOT NULL,
  PRIMARY KEY (`work_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;

通知:

CREATE TABLE `notifications` (
  `notification_id` int(11) NOT NULL AUTO_INCREMENT,
  `notification_userid` int(11) NOT NULL,
  `notification_workid` int(11) NOT NULL,
  `notification_stat` enum('1','0') NOT NULL,
  `notification_tarih` int(11) NOT NULL,
  PRIMARY KEY (`notification_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;

用户

CREATE TABLE `users` (
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `ip_address` varbinary(16) NOT NULL,
  `username` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `password` varchar(40) COLLATE utf8_unicode_ci NOT NULL,
  `salt` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
  `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `activation_code` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
  `forgotten_password_code` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
  `forgotten_password_time` int(11) unsigned DEFAULT NULL,
  `remember_code` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
  `created_on` int(11) unsigned NOT NULL,
  `last_login` int(11) unsigned DEFAULT NULL,
  `active` tinyint(1) unsigned DEFAULT NULL,
  `first_name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `last_name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `company` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `phone` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=8 ;

场景:当人们创建新作品时,表单值插入了作品表和通知表。通知表保存谁在做这些工作。可能不止一个人。我保存用户 ID 并加入用户表以查找谁。

在控制器中:

$data["works"]  =   $this->db->select("users.first_name, works.work_employees, works.work_name, works.work_baslangic, works.work_bitis, works.work_onay, works.work_onay_userid")->from("works")->join("users", "users.id = works.work_onay_userid", "LEFT")->get()->result_array(); 

在视图中:

foreach($works as $row):

在这一行,我编写了另一个 sql 来查找通知用户。但是我不想写另一个sql来查看,我想在控制器(或模型)上完成所有这些。我怎样才能做到这一点?

endforeach;
4

1 回答 1

0

在控制器中放置以下代码

// set to null so you can check against null value in view
$notifications = null;
foreach($works as $row)
    {

    $query = $this->db->query("SELECT * FROM `notifications` WHERE `notification_userid` = '{$row->works.work_onay_userid}'");// adapt query to your liking
    foreach($query->result() as $res)
            {
            $notifications[] = $res;
            }
    }
$data['notifications'] = $notifications;

这样,您已经在控制器中完成了查询,并在视图中获得了结果对象

于 2012-08-10T08:42:00.440 回答