php - Laravel 查询关系

标签 php laravel laravel-4

我正在尝试确定下表的数据库关系:

posts
======
id 
type_id
title 
content


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

其中 type_idposts_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/

相关文章:

php - 为什么 Laravel/Eloquent 不能使用 JOIN 进行预加载?

php - 通过引用函数传递字符串会加快速度吗? (php)

php - 使用 NGINX 作为 apache 的反向代理时,Wordpress 永久链接返回 404

php - 遍历特定行sql php

php - 单击提交按钮时不使用重定向

Laravel 5.2 开放式

php - access_token 过期后如何刷新 token

php - 在 laravel redis 中设置 ZADD 命令的选项

php - 如何使用 laravel 中的验证使输入日期字段大于或等于另一个日期字段

php - Laravel 使用 Eloquent 插入数据有两个有很多关系