我有一个简单的代码,该代码在Yii2中使用数据库事务,这将更新用户余额并将新记录添加到用户余额历史记录中。
//User model
public function changeBalance(UserBalanceHistory $balance)
{
$balance->balance = $this->balance;
$balance->user_id = $this->id;
$this->balance = $this->getBalance() + $balance->getDelta();
$transaction = Yii::$app->db->beginTransaction();
try {
if ($balance->save() && $this->save()) {
$transaction->commit();
return true;
}
} catch (Exception $e) {
Yii::error($e->getMessage());
}
$transaction->rollBack();
}
Run Code Online (Sandbox Code Playgroud)
我应该经常使用数据库事务来保存数据完整性。但是像上面那样处理数据库事务需要很多代码行,因此我创建了以下函数来调动我的代码:
function dbTransaction(callable $callback)
{
$transaction = Yii::$app->db->beginTransaction();
try {
//if callback returns true than commit transaction
if (call_user_func($callback)) {
$transaction->commit();
Yii::trace('Transaction wrapper success');
}
} catch (\Exception $e) {
$transaction->rollBack();
throw $e;
}
$transaction->rollBack();
}
Run Code Online (Sandbox Code Playgroud)
使用此功能,我可以处理如下交易:
//User …Run Code Online (Sandbox Code Playgroud) 我使用了Yii2多选下拉列表,它在创建时工作正常,但在更新时没有显示我选择的值!
形成:
$form->field($model, 'categories[]')
->dropDownList($model->CategoryDropdown,
[
'multiple'=>'multiple'
'class'=>'chosen-select input-md required',
]
)->label("Add Categories");
Run Code Online (Sandbox Code Playgroud)
模型:
public function getCategoryDropdown()
{
$listCategory = Category::find()->select('ID,name')
->where(['is_subcategory' => 'Yes'])
->andWhere(['status' => 'active','approved' => 'active'])
->all();
$list = ArrayHelper::map( $listCategory,'ID','name');
return $list;
}
Run Code Online (Sandbox Code Playgroud)
控制器:
public function actionCreate(){
...
$model->categories = implode(",",$_POST['Company']['categories']);
...
return $this->render('create', [
'model' => $model,
]);
}
public function actionUpdate($id)
{
$model = $this->findModel($id);
echo $model->categories; // 1,2,4,5 values already assigned
...
return $this->render('update', [
'model' => $model,
]);
}
Run Code Online (Sandbox Code Playgroud)
数据库:
1,2,4,5
当我更新我的recored时,如何在下拉列表中显示多个选定的值?
如何在Yii2中以一种形式使用多个模型?
在我的创建操作中,我可以保存到agenda_fiscalizacao表中,但在更新中,当我尝试加载表单时收到此错误:
Call to a member function formName() on array
Run Code Online (Sandbox Code Playgroud)
public function actionUpdate($id)
{
$model = $this->findModel($id);
$modelAgenda = AgendaFiscalizacao::findAll(['fiscalizacao_id' => $id]);
if ($model->load(Yii::$app->request->post()) && Model::loadMultiple($modelAgenda, Yii::$app->request->post())) {
$valid = $model->validate();
$valid = $modelAgenda->validade() && $valid;
if ($valid) {
$model->save(false);
$modelAgenda->save(false);
return $this->redirect(['view', 'id' => $model->id]);
}
}
return $this->render('update', [
'model' => $model,
'modelAgenda' => $modelAgenda
]);
}
Run Code Online (Sandbox Code Playgroud)
<?= $form->field($modelAgenda, 'agenda_id')->checkboxList(Agenda::combo(), ['class' => 'checkbox']) ?>
<?= $form->field($model, 'bioma_id')->dropDownList(Bioma::combo(), ['prompt' => $prompt]) ?>
<?= $form->field($model, …Run Code Online (Sandbox Code Playgroud) 基于https://github.com/wbraganca/yii2-dynamicform/wiki/Dynamic-Forms-With-Yii2-relation-trait-(VERY-EASY),我正在尝试实现动态表单.Create工作正常,但是在Update窗体中,如果我删除了任何动态表单元素,它就不会被删除,但如果我添加了Update操作,它就会被保存.这是我的更新代码
public function actionUpdate($id)
{
$modelAlumni = $this->findModel($id);
$modelsJob = $modelAlumni->jobs;
if ($modelAlumni->loadAll(Yii::$app->request->post()) && $modelAlumni->saveAll()) {
return $this->redirect(['view', 'id' => $modelAlumni->id]);
} else {
return $this->render('update', [
'modelAlumni' => $modelAlumni,
'modelsJob' => (empty($modelsJob)) ? [new Job] : $modelsJob
]);
}
}
Run Code Online (Sandbox Code Playgroud)
为什么不删除?
这是我的校友模特
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "alumni".
*
* @property integer $id
* @property string $name
* @property integer $gender
* @property integer $contact_number
* @property string …Run Code Online (Sandbox Code Playgroud) 我可以在Yii2模型页面(http://www.yiiframework.com/doc-2.0/yii-base-model.html)中看到,在"字段"部分中,您可以根据某些字段设置"不同的字段列表"上下文信息.例如,根据$ scenario或当前应用程序用户的权限,您可以返回不同的可见字段集或过滤掉某些字段."
但是,场景文档(http://www.yiiframework.com/doc-2.0/guide-structure-models.html#scenarios)表示场景用于为模型属性验证创建不同的上下文.
我正在使用Yii2 Restful API,我必须使用默认操作(actionIndex,actionView,...)从模型中获取数据并显示为API结果.我知道我可以覆盖那些方法(http://www.yiiframework.com/doc-2.0/guide-rest-controllers.html#extending-active-controller),但我怎么能说在那些方法中使用不同的方法字段(取决于不同的场景)?
我需要的是为actionIndex(项目列表)输出field1,field2,field3,但我想为actionView(项目列表)输出field1,field2,field3,field4.
我需要在GridView中对某些字段(asc,desc)进行排序,但计算相同的字段.看下面的代码: SearchModel:
class ObjectSearch extends Object {
use SearchModelTrait;
public function rules()
{
return [
['id', 'integer', 'min' => 1],
];
}
public function search($params)
{
$this->company_id = \Yii::$app->user->identity->companyId;
$query = Object::find()->where(['company_id' => $this->company_id]);
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => false,
]);
$dataProvider->setSort([
'attributes' => [
'id',
'name',
'lastReportResult' => [
'asc' => ['lastReportResult' =>SORT_ASC ],
'desc' => ['lastReportResult' => SORT_DESC],
'default' => SORT_ASC
],
'reportPercentDiff'
]
]);
if (!($this->load($params,'ObjectSearch') && $this->validate())) {
return $dataProvider;
}
$this->addCondition($query, …Run Code Online (Sandbox Code Playgroud) 我在主查询中有一个子查询,如下所示:
$subquery = (new Query())->select('COUNT(project_sup_id)')
->from('project_supervisors AS sup')
->where(['AND','sup.project_ref_id = p.project_id']);
$uQuery =(new Query())->select(['project_id','supcount' => $subquery])
->from('projects AS p')
->join('LEFT JOIN','project_supervisors AS sup','sup.project_ref_id = project_id')
->andWhere('IF(supcount>0, sup_project_status=1, project_status=1)');
Run Code Online (Sandbox Code Playgroud)
我正在尝试根据逻辑编写 where 条件,即,如果从子查询获得的计数大于零,则 where 条件必须为sup_project_status=1else project_status=1。在普通的Mysql中,很容易在where里面写if条件,但在yii2中我不明白如何写。
我试图从RestoFoods模型中删除数据:
RestoFoods::deleteAll(["restaurant_id"=>$postData['resto_id'], 'food_id NOT IN'=> [1,2] ]);
Run Code Online (Sandbox Code Playgroud)
我想要这个sql:
DELETE FROM `resto_foods` WHERE `restaurant_id`=1 AND (`food_id` NOT IN (1, 2));
Run Code Online (Sandbox Code Playgroud) 如何在 Yii 2.0 中使用多对多关系过滤连接/连接表中的值的结果?
我有以下表格
Member (id INT, name, ...)
Event (id INT, name, date, ...)
EventMemberConnection (id INT, event_id INT, member_id INT, accepted TINYINT(1) DEFAULT 0, foreign keys....)
Run Code Online (Sandbox Code Playgroud)
成员通过 EventMemberConnection 连接到事件,用一个整数告诉他们是被接受还是被拒绝
从模型文件 Event.php:
/**
* @return \yii\db\ActiveQuery
*/
public function getAcceptedMembers() {
return $this->hasMany(Member::className(), ['id' => 'member_id'])->viaTable('EventMemberConnection acceptedConnection', ['event_id' => 'id'])->onCondition(['acceptedConnection.accepted' => 1]);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getDeclinedMembers() {
return $this->hasMany(Member::className(), ['id' => 'member_id'])->viaTable('EventMemberConnection declinedConnection', ['event_id' => 'id'])->onCondition(['declinedConnection.accepted' => 0]);
}
Run Code Online (Sandbox Code Playgroud)
和查询,在休息控制器内:
public function prepareDataProvider() …Run Code Online (Sandbox Code Playgroud) 您可以在 yii2 的模型规则中输入密码模式吗?关于至少一个大写字符和至少一个数字的规则的提示?非常感谢
规则
['password', 'pattern' => '(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20}'],Run Code Online (Sandbox Code Playgroud)