B
B
Blud732014-12-18 14:53:53
Laravel
Blud73, 2014-12-18 14:53:53

How to pull in data from two tables?

Hello. Faced difficulties when using Laravel 4.2
There is a Blog model:

<?php
class Blog extends Eloquent {
  
  protected $table = 'blog';

    public function comments()
 		 {
    		return $this->hasMany('comments','page_id');
  		}
}

I have a controller with this function:
public function showWelcome()
  {
      $take_main = blog::where('active', '=', true)->take(3)->get();
      $total_comments = Blog::find(1)->comments()->where('active', '=', 1)->get()->count();
      print_r($total_comments);
    //return View::make('hello', array('blog' => $take_main));
  }

There are 2 tables: {BLOG:id,name,desc},{COMMENTS:id,page_id,desc}
I need to get the last 3 entries from the BLOG and find out how many comments there are for each entry (for 3 entries).
Please tell me how to do it so that all this would be obtained with a minimum load and effort.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
miki131, 2014-12-18
@miki131

Please read about relation in Eloquent and make your code much more human - one-to-many
Then read about lazy loading - eager-loading
Then you will understand what and how to do.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question