douxiji8707 2012-05-25 14:58
浏览 28

在这种情况下从视图调用模型的替代方法

I know we are suppose to call models from controller not the view but i'm in a situation that i have to do this

here it is :

I have a bloging script and in each user home page i want to show 10 posts and 5 comments for each post

So my controller looks something like

function get_posts($user_id){

   $blog_model = $this->load->model('bloging');
   $posts      = $blog_model->get_user_posts();
   $this->load->view('blog' , $posts )
}

Each post could have many comments so i have to get them too

So in my view i have

foreach($posts->result() as  $p ){

  echo $p->comment;

 /// getting comments
  $comment_model = $this->load->model('comments');
  $co = $comment_model->get_post_comments($p->id);
  foreach($co as $co )
   echo $co->comment;
  //////


}

I now this doesn't work like this as i have to use a helper or library or use a static method in model to do this( i'm using codeigniter , it might be different for other frame works )

But what alternative do i have ?

I can do this in controller , after getting posts use a foreach loop and get each post comments , put all comments in a 2d array($c_array[post_id][it's comments array])

Send them to the view with posts and in the view for each post look into the array for it's comments and .......

But it seams complicated , redundant and slower

i already have 4 joins on the post query and 2 joins on the comments query it would be 7 if i join these two

and also there is different limit for select in two query I'm fairly new to mvc . what is the right approach in this kind of situations ?

  • 写回答

2条回答 默认 最新

  • dqwh1219 2012-05-25 15:02
    关注

    Normally you would have a method on the post model to fetch comments for that post. Additionally i would normally have a method to make sure Comments are joined to the posts so you dont issue a comments query for every post.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。