2015-02-09 3 views
0

Это продолжение this question. Я учусь использовать соединения с моделями, но у меня проблемы с их работой.Показать все блоги, которые содержат теги

Вот моя структура таблицы:

Вот мой контроллер:

public function Tag($data=NULL) 
{ 
    $BlogData = Tag::with('blogs')->where('Name', $data)->get(); 
    return $last_query = end($BlogData); 
    return View::make('tag')->with('BlogData', $BlogData); 
} 

Вот мой Тэг Модель:

<?php 
class Tag extends Eloquent 
{ 
    protected $table = 'tags'; 

    public static $rules = array(
     'BlogTitle' => array('required'), 
     'BlogBody' => array('required') 
     ); 
     protected $fillable = array('BlogTitle', 'BlogBody'); 

    public function blogs(){ 
     return $this->belongsToMany('Blog'); 
    } 

} 

Вот мой блог Модель:

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

    public static $rules = array(
     'BlogTitle' => array('required'), 
     'BlogBody' => array('required') 
     ); 
     protected $fillable = array('BlogTitle', 'BlogBody'); 

     public function tags(){ 
     return $this->belongsToMany('Tag'); 
    } 

} 

Вот мое мнение:

@extends('layout.master') 
@section('body') 
    <div class="jumbotron"> 
    @foreach ($BlogData as $Blog) 
     Tag :{{$Blog->Name}} 

     {{$Blog->tags;}} 
    @endforeach 
    </div> 
@stop 

Как бы отобразить все блоги, которые имеют теги?

+0

Эрма ... что ваш вопрос? Я скопировал вопрос из вашего названия в ваш вопрос; имейте в виду, что вы всегда должны задавать вопрос в своем, ну, вопросе! –

ответ

0

Вы можете выбирать модели с помощью определенного отношения с whereHas:

$BlogData = Blog::with('tags')->whereHas('tags', function($q) use $data){ 
    $q->where('Name', $data); 
})->get(); 
Смежные вопросы