【问题标题】:Display all blogs which has the tags显示所有带有标签的博客
【发布时间】:2015-02-10 06:29:56
【问题描述】:

这是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

如何显示所有有标签的博客?

【问题讨论】:

  • 呃……你有什么问题?我已将您标题中的问题复制到您的问题中;请记住,您应该始终在您的问题中提出问题!

标签: php mysql laravel laravel-4


【解决方案1】:

可以通过whereHas的一定关系过滤模型:

$BlogData = Blog::with('tags')->whereHas('tags', function($q) use $data){
    $q->where('Name', $data);
})->get();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-22
    • 2012-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多