首页 > 解决方案 > 渴望加载过滤器(where 子句)?

问题描述

是否可以将 where 子句添加到模型上的急切加载方法中?例如:

class User extends Model {
  public function sources()
    {
        return $this->hasManyThrough(
            Source::class,          // The related model
            UserNetwork::class,  // The intermediate table that connects this model with the related model.
            'user_id',               // The intermediate table's column that connects to this model.
            'network_id',          // The related table's column that connects to the secondLocalKey.
            'id',               // This model's column that connects to the firstKey.
            'network_id'          // The intermediate table's column that connects the related model.
        )
            ->where('xyz_id', $this->xyz_id);
    }
}

这样做会User::with('sources')->get()返回具有源关系的用户集合,但源集合为空。当我运行User::first()->sources()->get()它时,它只返回带有实际数据的源集合。

急切加载不应该“急切加载”所有记录,而不是必须指定 first() 记录吗?

标签: laraveleloquenteager-loading

解决方案


推荐阅读