我正在尝试确定下表的数据库关系:
posts
======
id
type_id
title
content
posts_type
==========
id
type_name
其中 type_id
和 posts_type
(id) 相同,每个帖子都只有一种类型,
我如何在 Laravel 中定义它是一对一的关系吗?
谢谢
最佳答案
您可以使用一对多
关系,例如:
模型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);
模型帖子
:
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);
关于php - Laravel 查询关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26069415/