gpt4 book ai didi

php - 无法在 Yii 的连接表中插入记录

转载 作者:行者123 更新时间:2023-11-29 20:50:54 31 4
gpt4 key购买 nike

我是 Yii2 的新手。我有三个表 project、amenity 和一个联结表 project_amenity,代码如下:

项目模型:

<?php
namespace app\models;
use yii\db\ActiveRecord;

class Project extends \yii\db\ActiveRecord
{
public function getAmenities()
{
return $this->hasMany(Amenity::className(), ['id' => 'amenity_id'])->viaTable('project_amenity', ['project_id' => 'id']);
}

public function rules()
{
return [
[['name', 'city'], 'required'],
];
}
}

设施模型:

<?php
namespace app\models;
use yii\db\ActiveRecord;

class Amenity extends \yii\db\ActiveRecord
{
public function getProjects()
{
return $this->hasMany(Project::className(), ['id' => 'project_id'])->viaTable('project_amenity', ['amenity_id' => 'id']);
}
}

项目 Controller :

<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use app\models\Project;
use app\models\Amenity;
use yii\helpers\ArrayHelper;
class ProjectController extends Controller
{
public function actionCreate()
{
$project = new Project;
$amenities = ArrayHelper::map(Amenity::find()->all(), 'id', 'name');

if ($project->load(Yii::$app->request->post()) && $project->save()) {
return $this->render(['confirm', 'id' => $project->id]);
} else {
return $this->render('create', [
'project' => $project, 'amenities' => $amenities
]);
}
}
}

这是不完整的创建 View :

<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;
use yii\widgets\ActiveForm;

?>
<?php $form = ActiveForm::begin(); ?>
<table class="table">
<tr>
<td><?= $form->field($project, 'name'); ?></td>
</tr>
<tr>
<td ><?= $form->field($project, 'city'); ?></td>
</tr>
<tr>
<td><?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?></td>
</tr>
</table>

<?php ActiveForm::end(); ?>

ProjectAmenity连接模型

<?php
namespace app\models;
use yii\db\ActiveRecord;

class ProjectAmenity extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'project_amenity';
}
public function rules()
{
return [
[['project_id', 'amenity_id'], 'required']
];
}
}
?>

我能够显示关系数据,但无法插入。请建议如何在创建 View 上显示便利设施复选框,以及如何从创建 View 插入项目project_amenity表中的数据。

最佳答案

将设施属性添加到您的项目模型中:

public $amenities;

添加checkboxlist按您的观点:

<?= $form->field($project, 'amenities')->checkboxList($amenities) ?>

创建连接模型(如果尚不存在)。

保存后在创建操作中循环输入:

if ($project->load(Yii::$app->request->post()) && $project->save()) {
// checkboxlist fills amenities property with corresponding keys
foreach($project->amenities as $amenity_key) {
$project_amenity = new ProjectAmenity([
'project_id' => $project->id,
'amenity_id' => $amenity_key
]);
$project_amenity->save();
}
}

关于php - 无法在 Yii 的连接表中插入记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38071003/

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