database - Foreach and getting tags and categories from other tables -


i had hard time think title, hope explains.

posts table

+----+---------+-----------------+ | id |  title  |      text       | +----+---------+-----------------+ |  1 | title 1 | example | |  2 | title 2 | example | |  3 | title 3 | example | +----+---------+-----------------+ 

tags table

+----+--------+ | id |  tag   | +----+--------+ |  1 | jquery | |  2 | php    | |  3 | stack  | +----+--------+ 

category table

+----+------------+ | id |  category  | +----+------------+ |  1 | category 1 | |  2 | category 2 | |  3 | category 3 | +----+------------+ 

post tags relation table (same thing category)

+---------+--------+ | post_id | tag_id | +---------+--------+ |       1 |      1 | |       1 |      2 | |       2 |      3 | +---------+--------+ 

this result want see in view:

+---------+------------------+--------------------+------------+ |  title  |       text       |        tags        | categories | +---------+------------------+--------------------+------------+ | title 1 | example  | jquery, php        | category 2 | | title 2 | example  | stack              | category 1 | | title 3 | example  | jquery, php, stack | category 1 | +---------+------------------+--------------------+------------+ 

in controller have

public function index() {   $posts = posts::orderby('title', 'asc')->get();    return view::make('posts', array(     'posts' => $posts)   ); } 

and in view can list posts foreach loop

@foreach ($posts $post)   title: {{ $post->title }}   text: {{ $post->text }}   tags: ?   categories: ? @endforeach 

question best way tags , categories each post inside foreach loop?

shakil's tips right on spot , found looking for. surprised easy achieve. here did:

posts -model

class posts extends eloquent  {    protected $table = 'posts';     public function tags()    {      return $this->belongstomany('tags', 'post_tags', 'post_id', 'tag_id');    }     public function category()    {      return $this->belongstomany('category', 'post_categories', 'post_id', 'category_id');    } } 

view

@foreach ($posts $post)   title: {{ $post->title }}   text: {{ $post->text }}    tags:      @foreach ($post->tags $tag)       {{ $tag }}     @endforeach    categories:      @foreach ($post->categories $category)      {{ $category }}     @endforeach  @endforeach 

thanks help!


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -