Laravel 使用筛选器(where子句)快速加载?
是否可以将where子句添加到模型上的渴望加载方法中?例如:Laravel 使用筛选器(where子句)快速加载?,laravel,eloquent,eager-loading,Laravel,Eloquent,Eager Loading,是否可以将where子句添加到模型上的渴望加载方法中?例如: class User extends Model { public function sources() { return $this->hasManyThrough( Source::class, // The related model UserNetwork::class, // The intermediate table t
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()
时,它只返回包含实际数据的源集合
急切加载不是应该“急切加载”所有记录,而不是必须指定第一条()记录吗?
User::with('sources')->first()->sources
应该返回与User::first()->sources()->get()相同的内容;属于该用户的源记录的集合
get()
和first()
在您的案例中基本不相关。最大的区别是->sources
与->sources()->get()
;第一个是一个急切加载的集合,第二个是一个全新的查询,最终返回同一个集合。在我的例子中,它得到了所有的源,而不是我想要的源。我还必须按“xyz_id”列进行过滤。如果我添加where子句(filter),急切加载将停止工作。啊,我很抱歉,我错过了这是一个hasManyThrough()
。您可能需要为每个连接的表以及其他模型发布迁移。乍一看,与文档中给出的示例相比,它看起来有点不对劲,但我无法确定它。我发现了,但它没有提供一个hasManyThrough关系。你是说sources.xyz\u id==user\u networks.xyz\u id
?