gpt4 book ai didi

php - 相关(别名)模型上的Phalcon验证消息

转载 作者:行者123 更新时间:2023-12-03 07:59:27 29 4
gpt4 key购买 nike

假设我尝试保存以下数据,并且Songs模型的name属性上设置了Phalcon \ Mvc \ Model \ Validator \ PresenceOf验证器

// Get an existing artist
$artist = Artists::findFirst('name = "Shinichi Osawa"');

// Create an album
$album = new Albums();
$album->name = 'The One';
$album->artist = $artist;

$songs = array();

// Create a first song
$songs[0] = new Songs();
$songs[0]->name = 'Star Guitar';
$songs[0]->duration = '5:54';

// Create a second song
$songs[1] = new Songs();
$songs[1]->name = '';
$songs[1]->duration = '4:29';

// Assign the songs array
$album->songs = $songs;

// Save the album + its songs
if (!$album->save()) {
foreach ($album->getMessages() as $message) {
$message->getModel(); // this returns null since model is new
}
}

我将收到一条错误消息,提示必须输入“名称”。

问题:是否有内置的方式来获取发生错误的相关模型(在本例中为 $songs[1]),或者至少获取错误模型的别名/索引(在本例中为songs/1)?

最佳答案

找不到内置解决方案,但提出了解决方案。

基本模型

public function beforeValidation()
{
$session = $this->getService('session');

if (!$session->has('model:validation')) {
$validation = $indexes = [];
} else {
$modelName = get_called_class();
$validation = $session->get('model:validation');
if (!isset($validation[$modelName])) {
$validation[$modelName] = 0;
$indexes = $session->get('model:validation:relationIndex');
$indexes[] = $modelName;
} else {
$validation[$modelName]++;
// reset child indexes
$indexes = $session->get('model:validation:relationIndex');
$modelIndex = array_search($modelName, $indexes);
for ($i = $modelIndex + 1; $i < count($indexes); $i++) {
$modelName = $indexes[$i];
unset($validation[$modelName]);
unset($indexes[$i]);
}
$indexes = array_values($indexes);
}
}

$session->set('model:validation:relationIndex', $indexes);
$session->set('model:validation', $validation);
}

Controller
$session = $this->getDI()->get('session');
$session->remove('model:validation');
$session->remove('model:validation:relationIndex');

if (!$this->save()) {
var_dump($session->get('model:validation:relationIndex'));
var_dump($session->get('model:validation'));
}

关于php - 相关(别名)模型上的Phalcon验证消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31822202/

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