2014-04-30 123 views
0

嘿我想在我的帖子表和我的分类表之间建立关系。但我无法得到它的工作。Laravel数据库关系

这里是我的代码:

Posts.php (model) 

<?php 
class Post extends Eloquent 
{ 
    protected $table = "posts"; 

    public function categorie() 
    { 
     return $this->BelongsTo('Categorie'); 
    } 
} 

..

Categorie.php (model) 

<?php 
class Categorie extends Eloquent 
{ 
    protected $table = "categories"; 

    public function posts() 
    { 
     return $this->hasMany('Post'); 
    } 
} 

..

PageController.php (controller) 

<?php 
class PageController extends BaseController 
{ 
    public function getIndex() 
    { 
     $posts = Post::all(); 
     return View::make('layout.index')->with('posts', $posts); 
    } 
} 

我怎么能显示我的所有帖子现在他们所属的类别? 我知道如果我$post = Post::find(1)->categorie它返回属于帖子ID 1的分类,但我想返回我的所有帖子与分类

回答

1

当您在所有帖子中调用时,您需要加载关系。

$posts = Post::with('categorie')->get(); 

而且,该方法是不belongsToBelongsTo

此外,只是一个侧面说明。单数是类别,复数是类别。我有我的模型叫Category和关系叫category

+0

谢谢,这对我工作!和Categorie是荷兰:) – user3535369

+0

啊,道歉。 – ollieread