ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-11-18 13:32:24  阅读:265  来源: 互联网

标签:phalcon phalcon-orm 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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有