我有这样的查询:
$phsql = "
SELECT s.id AS siteId, s.name
FROM site s
INNER JOIN profiles p ON s.id = p.siteId
INNER JOIN users_profiles up ON up.profilesId = p.id
AND p.name = 'admin'
AND up.usersId = 2
";
我在模型方法中转换为以下内容:
$sites = Site::query()
->innerJoin('Profiles', 'Sites.id = Profiles.siteId')
->innerJoin('UsersProfiles', 'UsersProfiles.profilesId = Profiles.id')
->andWhere('Profiles.name = name')
->andWhere('UsersProfiles.usersId = :usersId:', ['userId' => $admin_id])->execute();
运行时会出现错误:
无法加载模型配置文件
请注意我在Site
型号中运行此功能。
更新
我试过了:
$sites = $this->modelsManager->createBuilder()
->from('myApp\Models\Site')
->innerJoin('myApp\Models\Profiles','myApp\Models\Site.id = myApp\Models\Profiles.siteId')
->andWhere("myApp\Models\Profiles.name = 'admin' ")
->where("myApp\Models\UsersProfiles.profilesId = 2")
->getQuery()
->execute();
现在它给出了错误:
未知的型号或别名' myApp \ Models \ UsersProfiles' (11),准备时:SELECT [myApp \ Models \ Site]。* FROM [myApp \ Models \ Site] INNER JOIN [myApp \ Models \ Profiles] ON myApp \ Models \ Site.id = myApp \ Models \ Profiles.siteId在哪里myApp \ Models \ UsersProfiles.profilesId = 2
答案 0 :(得分:3)
查看代码,我发现了两个问题:
1)你的第二行的> execute()应该抛出一个解析错误?
->innerJoin('Profiles', 'Sites.id = Profiles.siteId')->execute();
2)您必须为模型添加名称空间,请参阅下面的代码。
查询的一个工作示例:
Objects::query()
->columns([
'Models\Objects.id AS objectID',
'Models\ObjectLocations.id AS locationID',
'Models\ObjectCategories.category_id AS categoryID',
])
->innerJoin('Models\ObjectLocations', 'Models\Objects.id = Models\ObjectLocations.object_id')
->innerJoin('Models\ObjectCategories', 'Models\Objects.id = Models\ObjectCategories.object_id')
->where('Models\Objects.is_active = 1')
->andWhere('Models\Objects.id = :id:', ['id' => 2])
->execute();
您可以在关系中添加第三个参数(别名)以减少命名空间并提高代码可读性:
->innerJoin('Models\ObjectLocations', 'loc.object_id = obj.id', 'loc');
此处有更多信息:https://docs.phalconphp.com/en/latest/api/Phalcon_Mvc_Model_Criteria.html
另请注意:使用where()和andWhere()将where子句添加到查询中。在第一个查询示例中,子句在第二个连接语句中,而在Phalcon查询中,where子句被添加到整个查询中。如果您确实只希望这些条件用于第二个连接,请将它们添加到第二个连接参数,如下所示:
->innerJoin(
'Models\ObjectCategories',
'Models\Objects.id = Models\ObjectCategories.object_id AND ... AND ... AND ...'
)