我有这样的查询:
$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();
运行时报错:
Model Profiles could not be loaded
请注意,我在 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();
现在它给出了错误:
Unknown model or alias 'myApp\Models\UsersProfiles' (11), when preparing: SELECT [myApp\Models\Site].* FROM [myApp\Models\Site] INNER JOIN [myApp\Models\Profiles] ON myApp\Models\Site.id = myApp\Models\Profiles.siteId WHERE myApp\Models\UsersProfiles.profilesId = 2
最佳答案
查看您的代码,我发现了两个问题:
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 ...'
)
关于php - 执行查询时无法加载模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38165785/