2014-04-30 118 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