gpt4 book ai didi

php - 返回 Phalcon 模型中的虚拟列

转载 作者:行者123 更新时间:2023-12-02 17:35:11 26 4
gpt4 key购买 nike

我有一个模型 leads_contents_interactions 用于(简化的)表格:

CREATE TABLE `leads_contents_interactions` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`lead_content_id` bigint(20) unsigned DEFAULT NULL,
`created_on` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=59 DEFAULT CHARSET=utf8;

我想选择这些,除了 idlead_content_idcreated_on 列外,我还希望它返回一列 is_new 是这样的:

SELECT 
id,
lead_content_id,
created_on,
IF(created_on > DATE_SUB(NOW(),INTERVAL 1 DAY), 1, 0) AS is_new
FROM leads_contents_interactions;

现在我知道我可以用 PHQL 做到这一点,但是 leads_contents_interactions 最好不会被直接查询,我希望这个额外的列在被自然查询时返回:

$leads = $user->getRelated(
'leads',
array(
'Lead.deleted_by IS NULL',
'limit'=>1000
)
);

foreach($leads as $lead) {
foreach($lead->interactions as $interaction) {
echo $interaction->id."\t".$interaction->is_new.PHP_EOL;
}
}

铅模型(简化)

class Lead extends PersendlyModelAbstract {

public function initialize() {

// A lead has multiple interactions, `contents`, through the weak entity `leads_contents`
$this->hasManyToMany(
'id',
'LeadsContents',
'lead_id',
'id',
'LeadsContentsInteractions',
'lead_content_id',
array('alias' => 'interactions')
);
}
}

LeadsContents 模型(简化)

class LeadsContents extends PersendlyModelAbstract {

public function initialize() {
$this->belongsTo('lead_id', 'Lead', 'id', array('alias' => 'lead'));
$this->belongsTo('content_id', 'Content', 'id', array('alias' => 'content'));
$this->hasMany('id', 'LeadsContentsInteractions', 'lead_content_id');
}
}

LeadsContentsInteractions 模型(简化)

class LeadsContentsInteractions extends PersendlyModelAbstract {

public function initialize() {
$this->belongsTo('lead_content_id', 'LeadsContents', 'id', array('alias' => 'lead_content'));
}
}

最佳答案

如果您想要添加表中不存在但作为业务规则存在的列 (created_on > DATE_SUB(NOW(),INTERVAL 1 DAY), 1, 0),那么您需要添加该列模型本身的 afterFetch 方法中的规则:

http://docs.phalconphp.com/en/latest/reference/models.html#initializing-preparing-fetched-records

class LeadsContentsInteractions extends PersendlyModelAbstract 
{
public $isNew;

public function afterFetch()
{
$this->isNew = INSERT BUSINESS LOGIC HERE

}
}

但是应该注意,如果您随后在记录集上使用方法 toArray(),它将只使用表本身存在的列。

http://forum.phalconphp.com/discussion/498/afterfetch-

关于php - 返回 Phalcon 模型中的虚拟列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27618616/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com