【问题标题】:How to eager load in Laravel, while finding a specific entry如何在 Laravel 中急切加载,同时查找特定条目
【发布时间】:2013-02-28 15:07:00
【问题描述】:

我想用他们的用户配置文件急切地加载特定用户。我的表和类分别称为用户和用户。我的 Profiles 表和类是 user_profiles 和 UserProfile。

这是我正在尝试的,但它似乎不起作用

return User::with('user_profiles')->find(1);

【问题讨论】:

  • 仅供参考,如果您只是使用 find() 检索一条记录,则没有理由使用急切加载(使用“with()”)。数据库查询最终完全相同。仅当您从数据库中检索多条记录时,急切加载才有用。

标签: php laravel eloquent laravel-3


【解决方案1】:

我发现以下代码对于从一个模型实例中检索所有属性很有用。

User::with('posts')->get()->find(1);

返回这样的数组

id: 1,
name: 'john',
posts: [
  {
    id: 1,
    title: 'something',
  }
]

添加:

这会很慢,因为->get() 会从 DB 中检索所有数据。

所以

User::with('posts')->find(1)

【讨论】:

    【解决方案2】:

    您还需要在 User 类中定义一个 relationship method。比如:

    public function profile()
    {
       return $this->belongs_to('UserProfile');
    }
    

    然后你引用关系方法的名称:

    User::with('profile')->get()
    

    【讨论】:

    • 那行得通。我已经这样做了,但是我将函数命名为 userProfile,因此将其更改为仅配置文件会有所帮助。我没有意识到它使用了函数的名称。
    猜你喜欢
    • 2020-01-13
    • 2015-05-08
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 2016-04-09
    • 2019-07-08
    • 1970-01-01
    相关资源
    最近更新 更多