sanu
sanu

Reputation: 1068

laravel 5.1 many to many relation

HI This is my first project in Laravel 5.1. I am stuck in a laravel many to many relation please help I have a tables like

news

id | title | content

categories

id | title | cat_type

and the pivot table

category_news

id | category_id | news_id

and the models

 class News extends Model
{
   public function categories()
    {
        return $this->belongsToMany('App\Category');
    }
}

 class Category extends Model
{
   public function news() {

    return $this->belongsToMany('App\News');

  } 
}

how do i get all the news of cat_type=1 with it s related categories

please help

I tried

$news = News::whereHas('categories',
           function($query){    
              $query->where('cat_type','2');    
            })
            ->where('publish','1')
            ->orderBy('created_at', 'desc')
            ->take(5)
            ->get();//latest news

it gives a news but not related category please help thank you

Upvotes: 2

Views: 823

Answers (2)

Francesco Malatesta
Francesco Malatesta

Reputation: 679

You could also use Eager Loading for your needs.

In this case, all you should do is to write something like the following:

$categoryAndNews = Category::with('news')->where('cat_type',2)->first();

You could also define constraints in the relationships context.

$categoryAndNews = Category::with(['news' => function($query){
    $query->orderBy('created_at', 'desc')
    ->take(5);
}])->get();

Hope it will be useful!

More details about the topic here: http://laravel.com/docs/5.1/eloquent-relationships#constraining-eager-loads

Upvotes: 1

Basit
Basit

Reputation: 971

You can query the Category first like

$category = Category::where('cat_type',2)->first();
$news = $category->news()->where->where('publish','1')
        ->orderBy('created_at', 'desc')
        ->take(5)
        ->get();

Upvotes: 0

Related Questions