【问题标题】:Laravel 4 eager loading issues with relationshipLaravel 4急切加载关系问题
【发布时间】:2014-02-01 22:17:18
【问题描述】:

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

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

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');
    }
}

所以,我想获取我的所有物品并急切地加载所有者。这是我在控制器中的代码:

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"
    }
]

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

【问题讨论】:

    标签: php mysql laravel laravel-4 eloquent


    【解决方案1】:

    根据你在Item中的功能

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

    表示items表中的foreign key是id,用于与users表的关系,但您已将ownerId用作items表中的foreign key这是users 表的primary key。

    应该是这样的

    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时,传递给函数的第二个参数是当前表中的引用键(子键/本地键),这里items是当前表,它具有引用键@987654335 @ 因为它是 local-key,它与 users 表的 id 字段相关。

    【讨论】:

      【解决方案2】:

      试试这个

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

      【讨论】:

        猜你喜欢
        • 2014-12-28
        • 2014-08-13
        • 1970-01-01
        • 2021-12-01
        • 2021-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多