(laravel4)打印带有标签的帖子
我正在尝试打印我的标签和我的文章(称为教程) 如果我这样做,它会工作,但显然我总是只得到第一个标记,而不是属于教程的标记。从昨天起我就一直想让它工作,但我又一次被卡住了 教程模型:(laravel4)打印带有标签的帖子,laravel,eloquent,relationship,Laravel,Eloquent,Relationship,我正在尝试打印我的标签和我的文章(称为教程) 如果我这样做,它会工作,但显然我总是只得到第一个标记,而不是属于教程的标记。从昨天起我就一直想让它工作,但我又一次被卡住了 教程模型: class Tutorial extends Eloquent { protected $table = 'tutorials'; public function tags() { return $this->belongsToMany('Tag', 'tutorials_ta
class Tutorial extends Eloquent {
protected $table = 'tutorials';
public function tags() {
return $this->belongsToMany('Tag', 'tutorials_tags', 'tutorial_id');
}
}
标签型号:
class Tag extends Eloquent {
protected $table = 'tags';
public function tutorials() {
return $this->belongsToMany('Tutorial', 'tutorials_tags', 'tag_id');
}
}
主视图:
@foreach($tutorials as $tutorial)
<p>{{$tutorial->title}}</p>
<p>{{$tutorial->body}}</p>
@foreach($tags as $tag)
<p><b>Tags:</b> {{$tag->name}}</p>
@endforeach
<br>
@endforeach
@foreach($tutorials作为$tutorial)
{{$tutorial->title}
{{$tutorial->body}
@foreach($tags作为$tag)
标记:{{$tag->name}
@endforeach
@endforeach
您的控制器代码有点模棱两可,我假设您希望列出所有教程,以及与每个教程相关的标记
您可以利用Laravel的急切加载,提示:with('tags')
。基本上,它会告诉拉威尔,嘿,当你给我拿教程时,把它们“带着标签”带回来。因此,您不需要像尝试做的那样单独获取标记
因此,在您的HomeController中:
class HomeController extends BaseController
{
public function index()
{
$tutorials = Tutorial::with('tags')->where('draft', '=', 0)->get();
return View::make('home', array(
'tutorials' => $tutorials
));
}
}
你的看法是:
@foreach($tutorials as $tutorial)
<p>{{$tutorial->title}}</p>
<p>{{$tutorial->body}}</p>
@foreach($tutorial->tags as $tag)
<p><b>Tags:</b> {{$tag->name}}</p>
@endforeach
<br>
@endforeach
@foreach($tutorials作为$tutorial)
{{$tutorial->title}
{{$tutorial->body}
@foreach($tutorial->tags as$tag)
标记:{{$tag->name}
@endforeach
@endforeach
您还可以附加主页
视图的代码吗?您好^^主页视图现在已附加。再次感谢。您想列出所有教程,以及与之相关的标签吗?或者您只想获取第一个教程及其标记?我想获取所有教程以及相关标记。我建议您将标题编辑为类似“如何输出有说服力的模型及其关系?”的内容,谢谢!再次帮助我,你是我的英雄。谢谢下次我只提供提示!:P
@foreach($tutorials as $tutorial)
<p>{{$tutorial->title}}</p>
<p>{{$tutorial->body}}</p>
@foreach($tutorial->tags as $tag)
<p><b>Tags:</b> {{$tag->name}}</p>
@endforeach
<br>
@endforeach