Cakephp如何在选择查询中添加虚拟字段?

nbnkbykc  于 2022-11-11  发布在  PHP
关注(0)|答案(1)|浏览(158)

在前端,我必须显示所有收藏夹图标绿色取决于is_fav status true。
所以,我尝试创建一个API,我想在其中添加is_fav和所有产品实体。

{
       "id": 14,
       "title": "Orange",
       "price": 600,
       "is_fav" : true
}

因此,我尝试添加具有产品实体的is_fav,其中is_fav是虚拟函数。
在实体中我试过像下面

protected function _getIsFav()
{
    //to DO : I will write a query here 
    return true;
}

在查询中,我尝试在select中添加如下查询

$favorites = TableRegistry::getTableLocator()
            ->get( 'Products' )
            ->find()
            ->select([
                'id',
                'Products.id',
                'Products.title',
                'Products.price',
                'is_fav' => $this->is_fav,  //getting error 
            ])
;

我得到错误,我如何添加is_fav与产品实体。这是可能的吗?如果不是,我如何添加is_fav像我的json?

yvfmudvl

yvfmudvl1#

这对我很有效。CakePHP 4.3
在实体中

protected $_virtual = ['label'];

protected function _getLabel()
{
    return $this->name . ' - (' . $this->company. ')';
}

查询未提及虚拟字段

$customers = $this->Users->find()
        ->select(['id', 'name', 'company'])
        ->contain(['Roles' => function ($q) {
            return $q->select(['id','name','level','price_level'])
            ->where(['Roles.level' => 50]);
        }])
        ->order('Users.name');

然后输出JSON

[
    {
        "id": 1019,
        "name": "Abby xxxx",
        "company": "Abby yyy",
        "role": {
            "id": 4,
            "name": "Practitioner",
            "level": 50,
            "price_level": 2
        },
        "label": "Abby xxxx - (Abby yyy)"
    }
]

相关问题