php - Laravel 4 急切加载关系问题

标签 php mysql laravel laravel-4 eloquent

我有两个表,项目和用户。一个用户可以拥有多个项目,一个项目可以由一个用户拥有。

我的两个表有很多字段,但通过以下方式链接:

Item
----
ownerID

User
----
id

这些是将两个表链接在一起的字段,它们在我的数据库中设置为外键。

这是两个模型的简化版本:

class Item extends Eloquent {
    public function owner()
    {   
        return $this->belongsTo('User','id');
    }
}

class User extends Eloquent implements UserInterface, RemindableInterface {
    public function items()
    {
        return $this->hasMany('Item', 'ownerID');
    }
}

所以,我想获取我所有的项目并急切加载所有者。这是我在 Controller 中的代码:

class ItemsController extends BaseController {
    public function all(){
        $items = Item::with('owner')->get();
        return $items;
    }
}

(我正在返回 $items 以便我可以调试输出)

但是,这是我得到的输出:

[
    {
        "active":"1",
        "categoryID":"1",
        "created_at":"0000-00-00 00:00:00",
        "description":"Just a test item",
        "endDate":"2014-03-01 21:46:07",
        "id":"32",
        "name":"Test Item",
        "owner":null,
        "ownerID":"1",
        "section":"0",
        "updated_at":"0000-00-00 00:00:00"
    }
]

我不明白为什么 owner 为空?用户 ID 1 存在于我的数据库中,为什么它为空?

最佳答案

根据你在Item中的功能

public function owner()
{   
    return $this->belongsTo('User','id');
}

它表示,foreign keyitems表是 id用于与 users 的关系表,但你使用了 ownerId作为foreign keyitems表格是 primary keyusers表。

所以,应该是

public function owner()
{   
    // This model (child) with a local-key/field ownerId
    // in it's corresponding table(items) belongs to/relates to the
    // user model (parent) with primary-key id in corresponding (users) table
    return $this->belongsTo('User','ownerID');
}

在使用 belongsTo/reverse 时传递给函数的第二个参数是当前表中的引用键(child-key/local-key),这里是items是当前表,它有引用键 ownerId因为它是local-key这与 id 有关领域users表。

关于php - Laravel 4 急切加载关系问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21504379/

相关文章:

php - Laravel 使用自定义命名空间扩展 Illuminate\Foundation\Testing\TestCase

php - 检查 Laravel 包服务提供者中是否存在迁移

PHP (Laravel) 依赖注入(inject)基础

javascript - Gummer-psn php 安装时需要帮助

mysql - 此时是否可以使用 Nuodb 作为 MySQL 的 "drop-in"替代品?

php - 编辑 html 表行并使用 php 将其更新到 mysql 表中

mysql - SQL中的关键字和子句有什么区别?

php - SQL 在第 1 行处使用准备好的语句 "near ' ?,?,?,?) 引发语法错误

javascript - 如果禁用了javascript,如何禁用网站

php - Doctrine - 计算来自不同表的记录