Laravel查询关系
问题描述:
我试图确定数据库的关系,以下表格:Laravel查询关系
posts
======
id
type_id
title
content
posts_type
==========
id
type_name
凡type_id
和posts_type
(ID)是相同的,其中每个岗位敢拿只有一种类型, 怎么办我在Laravel中定义这是一对一的关系吗?
感谢
答
可以使用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);
这是两个单独的modles吧? – user3150060 2014-09-26 22:59:25
是的,两者都是不同的型号。 – 2014-09-26 22:59:46
非常感谢您的帮助 – user3150060 2014-09-26 23:01:09