编程语言
首页 > 编程语言> > PHP-执行查询时无法加载模型

PHP-执行查询时无法加载模型

作者:互联网

我有这样的查询:

$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

请注意,我正在网站模型中运行它.

更新资料

我尝试了这个:

    $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子句添加到查询中.在第一个查询示例中,子句位于第二个join语句内,而在Phalcon查询中,where子句将添加到整个查询中.如果您确实只希望那些条件用于第二个联接,则将它们添加到第二个联接参数中,如下所示:

->innerJoin(
   'Models\ObjectCategories', 
   'Models\Objects.id = Models\ObjectCategories.object_id AND ... AND ... AND ...'
)

标签:phalcon,phalcon-orm,php
来源: https://codeday.me/bug/20191118/2028329.html