我有以下模型类(示例灵感来自 documentation on github ):
<?php
class Post extends Model {
public function user() {
return $this->belongs_to('User');
}
}
class User extends Model {
public function posts() {
return $this->has_many('Post'); // Note we use the model name literally - not a pluralised version
}
}
现在我可以执行以下操作(效果很好):
// Select a particular user from the database
$user = Model::factory('User')->find_one($user_id);
// Find the posts associated with the user
$posts = $user->posts()->find_many();
// Select a particular post from the database
$post = Model::factory('Post')->find_one($post_id);
// Find the user associated with the post
$user = $post->user()->find_one();
但我也想做以下事情:
$posts = Model::factory('Post')->find_many();
foreach ($posts as $post) {
echo($post->user()->find_one()->username); // generates a query each iteration
}
不幸的是,这会为每次迭代创建一个查询。有没有办法告诉 Paris 或 Idiorm 在第一个 find_many 查询中获取关联信息?
您应该如何通过 Paris 检索信息以尽量减少查询次数?我不想手动指定连接条件(这就是我使用 Paris 而不是 Idiorm 的原因)
最佳答案
我是 Paris 和 Idiorm 项目的当前维护者。不幸的是,您在这里描述的是自定义查询的情况,而不是巴黎旨在解决的问题。 Paris 和 Idiorm 的理念是尽可能遵循 80/20 原则,并且您的用例位于 20 中。
了解您最终如何解决这个问题会很有趣。
关于php - 如何使用 Idiorm 和 Paris 仅通过一个查询从关联表中检索信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12597197/