Laravel 4 创建帖子类型关系
题
我试图理解雄辩的 ORM。我创建了一个基本的帖子博客。
我想为我的帖子添加帖子类型,每个帖子只能有一种类型。
帖子类型:新闻发布视频帖子博客文章
数据库结构:
桌子:档案
id
title
content
created_at
updated_at
excerpt
deleted_at
status
桌子:类型
id
name
created_at
updated_at
桌子:档案类型
id
archive_id
type_id
created_at
updated_at
楷模:
模型:档案
class Archive extends Eloquent
{
protected $fillable = array('title', 'content', 'excerpt');
public function type()
{
return $this->belongsToMany('Type');
}
}
模型:类型
class Type extends Eloquent
{
protected $fillable = array('name');
}
这在运行时有效:
Archive::with(array('type'))->orderBy('id', 'DESC')->get();
但它返回一个集合,我认为这是错误的,因为它应该只返回一个结果。
我遇到的另一个问题是如何向 archive_type
新帖子的数据库。
任何帮助表示赞赏。
解决方案
无论有 0 个还是 100 万个结果,始终返回一个集合。此规则的唯一例外是“查找”方法,它们旨在用作主键查找方法,在这种情况下,只能有零个或一个结果,因此它将返回它找到的模型,而不是一个集合。您在查找时遇到的行为符合预期。
如果您想退回第一个模型,您可以放置->first()
在你之后->get()
.创建新的存档类型 inc。你应该做的关系:
// 获取我们的存档和类型模型
$archive = Archive::with(array('type'))->orderBy('id', 'DESC')->get()->first();
$type = Type::where('name','=','video')->get()->first();//附加它们!
$archive->type()->attach($type);
编辑:如何在刀片模板中显示。
要将集合(或与此相关的任何数据)传递到视图,请在控制器中执行以下操作:
return View::make('yourview')->with('archives', $archives);
要循环浏览刀片模板中的集合,请使用 @foreach
@foreach ($archives as $archive)
<p>This is archive id is {{ $archive->id }}</p>
@endforeach
否则,如果您只浏览了一个模型而不是一个集合,您可以这样做
<p>This is archive id is {{ $archive->id }}</p>
如果您要问“我如何在视图中显示集合中的第一个模型”,简单的答案是,首先从集合中获取模型,然后将其传递到您的视图,其他任何事情都需要“业务逻辑”在你看来。