2014-09-26 142 views
2

我試圖確定數據庫的關係,以下表格:Laravel查詢關係

posts 
====== 
id 
type_id 
title 
content 


posts_type 
========== 
id 
type_name 

type_idposts_type(ID)是相同的,其中每個崗位敢拿只有一種類型, 怎麼辦我在Laravel中定義這是一對一的關係嗎?

感謝

回答

2

可以使用One-To-Many關係,例如:

型號PostType

class PostType extends Eloquent { 

    protected $table = 'posts_type'; 

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

} 

// Get PostType (whereId=1) with all related posts 
$postType = PostType::with('posts')->find(1); 

型號Post

class Post extends Eloquent { 

    protected $table = 'posts'; // Optional 

    public function postType() 
    { 
     return $this->belongs('PostType', 'type_id', 'id'); 
    } 

} 

// Get Post (whereId=1) with it's related PostType 
$post = Post::with('postType')->find(1); 
+0

這是兩個單獨的modles吧? – user3150060 2014-09-26 22:59:25

+0

是的,兩者都是不同的型號。 – 2014-09-26 22:59:46

+0

非常感謝您的幫助 – user3150060 2014-09-26 23:01:09