在 Kohana 中执行搜索以导航 2 个模型之间的关系
假设我有 2 个模型用户和位置。模型之间存在明确的关系,允许我执行此操作:
$user->location->name;
我不知道是否可能,但我可以使用类似以下内容执行搜索:
$user->location->where('name', '=', 'Paris')->find();
返回其位置名为巴黎的用户吗?
Let's say I have 2 models user and location. There is a defined relationship between the models that allows me to do this:
$user->location->name;
I don't know if it's possible but can I perform a search using something like:
$user->location->where('name', '=', 'Paris')->find();
that returns me the users that its location is named Paris?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简而言之,你可以。这就是原因。
当您调用 find 方法时,ORM 会遍历要添加到查询中的所有待处理属性,添加它们并执行查询。在您的示例中,您有两个待定规则要添加到您的查询中。您显然定义了第一个 -
where('name', '=', 'Paris')
,第二个隐藏在关系$user->location
中>。当您从关系调用 ORM 属性时,它实际上返回关系中定义的 ORM 对象,该对象未加载,但在其内部有一个待处理的
where
子句和一个join
目的。因此,当您最终调用find
方法时,您是在使用两个where
子句和一个join
的位置对象上调用它。In short you can. Here is why.
When you call the
find
method the ORM goes through all of the pending properties to be added to the query, adds them and executes the query. In your example you have two pending rules to be added to your query. The first one you are defining obviously -where('name', '=', 'Paris')
, the second one is hidden in the relationship$user->location
.When you call an ORM property from a relationship, it actually returns an ORM object defined in the relationship which is not loaded, but has a pending
where
clause and ajoin
in its object. So when you call thefind
method in the end, you are calling it on the location object with twowhere
clauses and onejoin
.