外键未存储在 Yii 中

2024-02-25

我有一个这样的数据库

====Group=====
id
name

====Member====
id
group_id
firstname
lastname
membersince


Now as group_id is foreign key then when I will save Group tabale then the group_id should be save with that number.
In relations I have made relations for Group is



     public function relations()
  {
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
      'member' => array(self::HAS_MANY, 'Member', 'groupid'),
    );
  }

在会员模型中我的关系就像这样

 public function relations()
  {
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
      'group' => array(self::BELONGS_TO,'Group','groupid'),
    );
      }

现在,我将以单一形式保存两个模型(示例在这里[http://www.yiiframework.com/wiki/19/how-to-use-a-single-form-to-collect-data-for-two-or-more-models] http://www.yiiframework.com/wiki/19/how-to-use-a-single-form-to-collect-data-for-two-or-more-models)两个模型已成功保存,但外键未存储。那么有人可以告诉我我哪里做错了吗?

[控制器代码] 集团控制器

<?php

class GroupController extends Controller
{
  /**
   * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
   * using two-column layout. See 'protected/views/layouts/column2.php'.
   */
  public $layout='//layouts/column2';

  /**
   * @return array action filters
   */
  public function filters()
  {
    return array(
      'accessControl', // perform access control for CRUD operations
    );
  }

  /**
   * Specifies the access control rules.
   * This method is used by the 'accessControl' filter.
   * @return array access control rules
   */
  public function accessRules()
  {
    return array(
      array('allow',  // allow all users to perform 'index' and 'view' actions
        'actions'=>array('index','view'),
            'users'=>array('*'),
      ),
      array('allow', // allow authenticated user to perform 'create' and 'update' actions
        'actions'=>array('create','update'),
        'users'=>array('@'),
      ),
      array('allow', // allow admin user to perform 'admin' and 'delete' actions
        'actions'=>array('admin','delete'),
        'users'=>array('admin'),
      ),
      array('deny',  // deny all users
        'users'=>array('*'),
      ),
    );
  }

  /**
   * Displays a particular model.
   * @param integer $id the ID of the model to be displayed
   */
  public function actionView($id)
  {
    $this->render('view',array(
      'model'=>$this->loadModel($id),
    ));
  }

  /**
   * Creates a new model.
   * If creation is successful, the browser will be redirected to the 'view' page.
   */
  public function actionCreate()
  {
    $model=new Group;
    $member=new Member;

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['Group'],$_POST['Member']))
    {
      //Populate input data to $Group and $Member
      $model->attributes=$_POST['Group'];
      $member->attributes=$_POST['Member'];

      //Validate both $Group and $Member
      //$validate = $model->validate();
      //$validate = $member->validate() && validate;

#      if($validate){
#        ($model->save() & $member->save())
#        $this->redirect(array('view','id'=>$model->id));
#      }
      if($model->save() & $member->save())
        $this->redirect(array('view','id'=>$model->id));
    }

    $this->render('create',array(
      'model'=>$model,
      'member'=>$member,
    ));
  }

  /**
   * Updates a particular model.
   * If update is successful, the browser will be redirected to the 'view' page.
   * @param integer $id the ID of the model to be updated
   */
  public function actionUpdate($id)
  {
    $model=$this->loadModel($id);
    $member = Member::model()->findByPk( $member['name'] );
    //$member =  new Member;
    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['Group'],$_POST['Member'])) {
    $model->attributes=$_POST['Group'];
    $member->attributes=$_POST['Member'];

      if($model->save()&$member->save())
        $this->redirect(array('view','id'=>$model->id));
    }

    $this->render('create',array(
      'model'=>$model,
      'member'=>$member,
    ));
  }

  /**
   * Deletes a particular model.
   * If deletion is successful, the browser will be redirected to the 'admin' page.
   * @param integer $id the ID of the model to be deleted
   */
  public function actionDelete($id)
  {
    if(Yii::app()->request->isPostRequest)
    {
      // we only allow deletion via POST request
      $this->loadModel($id)->delete();

      // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
      if(!isset($_GET['ajax']))
        $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }
    else
      throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
  }

  /**
   * Lists all models.
   */
  public function actionIndex()
  {
    $dataProvider=new CActiveDataProvider('Group');
    $this->render('index',array(
      'dataProvider'=>$dataProvider,
    ));
  }

  /**
   * Manages all models.
   */
  public function actionAdmin()
  {
    $model=new Group('search');
    $model->unsetAttributes();  // clear any default values
    if(isset($_GET['Group']))
      $model->attributes=$_GET['Group'];

    $this->render('admin',array(
      'model'=>$model,
    ));
  }

  /**
   * Returns the data model based on the primary key given in the GET variable.
   * If the data model is not found, an HTTP exception will be raised.
   * @param integer the ID of the model to be loaded
   */
  public function loadModel($id)
  {
    $model=Group::model()->findByPk($id);
    if($model===null)
      throw new CHttpException(404,'The requested page does not exist.');
    return $model;
  }

  /**
   * Performs the AJAX validation.
   * @param CModel the model to be validated
   */
  protected function performAjaxValidation($model)
  {
    if(isset($_POST['ajax']) && $_POST['ajax']==='group-form')
    {
      echo CActiveForm::validate($model);
      Yii::app()->end();
    }
  }
}

会员控制器

<?php

class MemberController extends Controller
{
  /**
   * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
   * using two-column layout. See 'protected/views/layouts/column2.php'.
   */
  public $layout='//layouts/column2';

  /**
   * @return array action filters
   */
  public function filters()
  {
    return array(
      'accessControl', // perform access control for CRUD operations
    );
  }

  /**
   * Specifies the access control rules.
   * This method is used by the 'accessControl' filter.
   * @return array access control rules
   */
  public function accessRules()
  {
    return array(
      array('allow',  // allow all users to perform 'index' and 'view' actions
        'actions'=>array('index','view'),
        'users'=>array('*'),
      ),
      array('allow', // allow authenticated user to perform 'create' and 'update' actions
        'actions'=>array('create','update'),
        'users'=>array('@'),
      ),
      array('allow', // allow admin user to perform 'admin' and 'delete' actions
        'actions'=>array('admin','delete'),
        'users'=>array('admin'),
      ),
      array('deny',  // deny all users
        'users'=>array('*'),
      ),
    );
  }

  /**
   * Displays a particular model.
   * @param integer $id the ID of the model to be displayed
   */
  public function actionView($id)
  {
    $this->render('view',array(
      'model'=>$this->loadModel($id),
    ));
  }

  /**
   * Creates a new model.
   * If creation is successful, the browser will be redirected to the 'view' page.
   */
  public function actionCreate()
  {
    $model=new Member;

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['Member']))
    {
      $model->attributes=$_POST['Member'];
      if($model->save())
        $this->redirect(array('view','id'=>$model->id));
    }

    $this->render('create',array(
      'model'=>$model,
    ));
  }

  /**
   * Updates a particular model.
   * If update is successful, the browser will be redirected to the 'view' page.
   * @param integer $id the ID of the model to be updated
   */
  public function actionUpdate($id)
  {
    $model=$this->loadModel($id);

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['Member']))
    {
      $model->attributes=$_POST['Member'];
      if($model->save())
        $this->redirect(array('view','id'=>$model->id));
    }

    $this->render('update',array(
      'model'=>$model,
    ));
  }

  /**
   * Deletes a particular model.
   * If deletion is successful, the browser will be redirected to the 'admin' page.
   * @param integer $id the ID of the model to be deleted
   */
  public function actionDelete($id)
  {
    if(Yii::app()->request->isPostRequest)
    {
      // we only allow deletion via POST request
      $this->loadModel($id)->delete();

      // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
      if(!isset($_GET['ajax']))
        $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }
    else
      throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
  }

  /**
   * Lists all models.
   */
  public function actionIndex()
  {
    $dataProvider=new CActiveDataProvider('Member');
    $this->render('index',array(
      'dataProvider'=>$dataProvider,
    ));
  }

  /**
   * Manages all models.
   */
  public function actionAdmin()
  {
    $model=new Member('search');
    $model->unsetAttributes();  // clear any default values
    if(isset($_GET['Member']))
      $model->attributes=$_GET['Member'];

    $this->render('admin',array(
      'model'=>$model,
    ));
  }

  /**
   * Returns the data model based on the primary key given in the GET variable.
   * If the data model is not found, an HTTP exception will be raised.
   * @param integer the ID of the model to be loaded
   */
  public function loadModel($id)
  {
    $model=Member::model()->findByPk($id);
    if($model===null)
      throw new CHttpException(404,'The requested page does not exist.');
    return $model;
  }

  /**
   * Performs the AJAX validation.
   * @param CModel the model to be validated
   */
  protected function performAjaxValidation($model)
  {
    if(isset($_POST['ajax']) && $_POST['ajax']==='member-form')
    {
      echo CActiveForm::validate($model);
      Yii::app()->end();
    }
  }
}

None

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

外键未存储在 Yii 中 的相关文章

  • 为什么这评估为 true

    为什么这评估结果为真
  • 所有 PHP 相等比较都是对称的吗?

    Is a b总是等价于 b a 我认为在 JavaScript 中 由于强制转换 有一些奇怪的情况并非如此 I think ide https stackoverflow com questions 4752579 are all php
  • 正则表达式上的换行符

    我试图替换两个标签之间的所有内容 但我无法构建正确的表达式 这就是我所做的
  • Symfony2:为什么请求传递到受 Symfony2 中 AppCache 影响的 Kernel.Terminate EventListener

    在我的 Symfony2 2 应用程序中 我使用 onKernelTerminate EventListener 以便我可以在渲染响应后进行一些 繁重 处理 以便用户收到更快的响应时间 在我的控制器中 我在请求上设置了一个属性 以便当事件侦
  • 简单的 PHP 回显代码不起作用

    这是我的 html 和 php 脚本 h1 Bob s Auto Parts h1 table width 100 tr tr table 为什么这个输出会出现一个 gt 我希望它是 这有效 仅有的 这是输出 鲍勃的汽车零件 鲍勃
  • php源代码到PO文件生成器

    我必须将我的所有回显 打印字符串转换为PHP源代码代码文件到PO file 为了语言翻译 有批次吗对流器可用于相同的 我如何做到这一点 make gettext在您的服务器上运行 setup a 翻译适配器 例如带有 gettext 适配器
  • PHP 无法打开流:是一个目录

    非常简单的 PHP 脚本 我在我亲自设置的 Ubuntu Web 服务器上的 EE 模板中运行 我知道这与权限有关 并且我已经将我尝试写入的目录的所有者更改为 Apache 用户 我得到的错误是 遇到 PHP 错误 严重性 警告 消息 fi
  • PHP - 类外 use 关键字和类内 use 关键字的区别

    伙计们 美好的一天 只是想问一下有什么区别use之外的class and use在 的里面class 我也用谷歌搜索过 但我的问题与答案不匹配 Example namespace App Http Controllers Auth use
  • 使用 PHP PayPal REST API 退款?

    我正在开发一个集成到 PayPal 的 REST API 中的 PHP 应用程序 我正确处理了事务并将事务 ID 保存到 MySQL 数据库中 我现在正在尝试退款 但无法让它停止给出 传入 JSON 请求未映射到 API 请求 错误 有人对
  • 对 SimpleXML 数据进行排序和分组

    我正在对 XML 文件中的出版物数据进行排序和分组 我目前使用的方法效果很好大部分情况下 尽管我觉得有一种更有效的方法来完成我想要完成的任务 以下是目标节点的示例
  • 在 Yii 的标准中如何获得计数 (*)

    我正在尝试构建一个具有以下内容的查询group by属性 我正在尝试得到id和count它一直告诉我count is invalid列名 我怎样才能得到count来自group by询问 工作有别名 伊伊 1 1 11 其他不及格 crit
  • PHP 扩展开发入门 [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 请推荐有关 PHP 低 级 modules 编程接口的帮助文章或教程 搜索我的书签 我发现的唯一链接是
  • 如何在 Zend MVC 中实现 SSL

    我之前已经通过使用特定的安全文件夹 例如服务器上的 https 文件夹与 http 文件夹 实现了安全页面 我已经开始使用 Zend Framework 并希望应用程序的某些部分 例如登录 使用 https 我在谷歌上搜索过 甚至在这里搜索
  • Facebook PHP SDK - 如何获取访问令牌?

    我正在尝试从我的应用程序在用户的 Facebook 墙上发帖 用户授予应用程序在他的墙上发布的权限 并且我在数据库中有用户ID 我需要自动发送帖子 而无需用户再次登录 我的代码是 try require once dirname FILE
  • 如何在 phalcon 框架中同时连接多个数据库在模型类中同时使用两个而不仅仅是一个

    在我的代码中我有两个数据库ABC and XYZ 我想在同一模型中使用两个数据库 而不是 phalcon 中的解决方案是什么 如何为此实现多个数据库连接 one
  • 如何使用 php 在 sql 查询中转义引号?

    我有一个疑问 sql SELECT CustomerID FROM tblCustomer WHERE EmailAddress addslashes POST username AND Password addslashes POST p
  • 从字符串中获取数字

    我有一个字符串 例如 lorem 110 ipusm 我想获取 110 我已经尝试过这个 preg match all 0 9 string ret 但这正在返回 Array 0 gt 1 1 gt 1 2 gt 0 我想要这样的东西 Ar
  • 如何清除 APC 缓存而不使 Apache 崩溃?

    如果 APC 存储大量条目 清除它们会导致 httpd 崩溃 如果 apc clear cache user 花费的时间超过 phps max execution time 调用 apc clear cache 的脚本 将在之前被 php
  • 如何使用 php 将 *.xlsb 转换为数组或 *.csv

    我正在尝试转换 xlsb文件到php array or csv文件 或至少 xls 我尝试使用PHPExcel 但看起来它无法识别该文件中的内容 我注意到 你可以重命名 xlsb文件到 zip文件 然后使用命令行解压缩unzip zip 之
  • 使用 PHP 将 latin1_swedish_ci 转换为 utf8

    我有一个数据库 里面充满了类似的值 Dhaka 应该是 Dhaka 因为我在创建数据库时没有指定排序规则 现在我想修复它 我无法从最初获取数据的地方再次获取数据 所以我在想是否可以在 php 脚本中获取数据并将其转换为正确的字符 我已将数据

随机推荐

  • Python 3 imaplib.fetch TypeError:无法将字节连接到 int

    我有一些代码可以获取 IMAP 电子邮件 并且在 Python 2 中运行得很好 在 Python3 中 我收到以下错误 回溯 最近一次调用最后一次 文件 mail py 第 295 行 位于项目 返回消息 x 文件 mail py 第 1
  • Windows 服务如何确定其 ServiceName?

    我查了一下 找不到一个简单的问题 Windows 服务如何确定其启动的 ServiceName 我知道安装可以破解注册表并添加命令行参数 但从逻辑上讲 这似乎是这样should没有必要 所以才有这个问题 我希望比注册表黑客更干净地运行单个二
  • 如何删除 pandas 数据框中具有负值的所有行?

    我有一个混合了列数据类型 float64 和对象的数据框 我需要动态删除所有具有负值的行 这是我到目前为止所拥有的 df df df gt 0 all axis 1 但因为有些列不是数字 所以它基本上会擦除整个 df 我怎样才能构建这个只考
  • 安装unf_ext(0.0.7.2)时出错,Bundler无法继续

    我试图将 diaspora 安装到本地主机中 我删除了Gemfile lock文件并尝试过bundle install我看到了这个 这些是我已经尝试过的事情 ARCHFLAGS Wno error unused command line a
  • Terraform 抛出“groupName 无法与参数子网一起使用”或“VPC 安全组不能用于非 VPC 启动”

    当试图弄清楚如何配置aws instance使用 AWS VPC 时会发生以下错误 Error launching source instance InvalidParameterCombination The parameter grou
  • 用于创建新元素的突变观察者

    我试图在创建特定 div 时使函数关闭 用最简单的话来说 我有这样的事情 a href Click me a 之前 我让突变事件监听 div bar 的创建 像这样 bar live DOMNodeInserted function eve
  • 程序集绑定重定向和代码分析

    我在 Visual Studio 2010 的 Mvc 3 0 0 0 项目中使用 DotNetOpenAuth 引用 System Web Mvc 版本 1 0 0 0 我正在使用程序集绑定重定向 如下所示
  • 使用 Flex 生成的文件时出现问题

    我正在尝试设置一个使用 flex 的项目 fast lex 而不是 adobe 我在 Ubuntu 上运行 并通过 apt get 方法安装了 flex 我用谷歌搜索了编译错误 我要么找到了围绕它创建自己的补丁的人 要么找到了很多论坛 人们
  • 如何简单地显示 YQL 的 xml 输出或将 JSON 输出为 html

    因此 我一直在研究一种从页面中抓取数据并显示它的方法 以与源格式大致相同的格式 我发现了 YQL 我发现它很棒 除了我不知道如何显示整个输出 没有什么特别的 除了基本格式 YQL输入代码为 select from html where ur
  • Python:无法分配给文字

    我的任务是编写一个程序 要求用户输入 5 个名称并将其存储在列表中 接下来 它随机选择这些名字之一 并宣布该人为获胜者 唯一的问题是 当我尝试运行它时 它说can t assign to literal 这是我的代码 import rand
  • 是否可以找到当前正在使用的 tmux 套接字?

    我正在尝试获取当前正在使用的 tmux 套接字列表 但到目前为止我想出的最佳解决方案是签入 tmp tmux 或 TMPDIR 据我所知 即使当前没有 tmux 会话正在使用这些套接字 tmux 也会将这些套接字保留一段时间 因此 我希望有
  • Django 表单未使用 ModelChoiceField 保存 -foreignkey

    我的网站上有多个表单 可以将信息保存到我的 PostgreSQL 数据库中 我正在尝试创建一个表单来保存我的设置模型的信息 class Set models Model settitle models CharField Title max
  • 没有在 DLL 项目中创建 WPF 窗口?

    Visual Studio 不允许我在 DLL 项目中创建 WPF 窗口是否有原因 我通过在应用程序项目中创建一个窗口并将其复制到我的 DLL 项目来 解决 这个问题 我还发现我可以创建一个 UserControl 并将基类更改为 Wind
  • 连接 Java 和 Python Flask

    我有一个简单的 Flask API from flask import Flask jsonify app Flask name app route def hello world return Hello World app route
  • 如何通过批处理文件执行cmd命令?

    我想编写一个批处理文件 它将按给定顺序执行以下操作 Open cmd 运行cmd命令cd c Program files IIS Express 运行cmd命令iisexpress path C FormsAdmin Site port 8
  • 在 Android 上隐藏 Toast

    我正在开发一个应用程序 它使用系统活动将联系人添加到手机内存中 此外部活动在保存联系人后启动 Toast 有没有可能摆脱它 如果我可以获得对它的引用来调用 cancel 或取消所有排队的 Toast 那就完美了 有Toast管理器吗 如果您
  • 将字体大小调整为绘图设备的大小

    我经常遇到必须调整输出图像大小的情况 不幸的是 这意味着通常我必须调整字体大小 以使内容可读 例如 如果下面的图 library ggplot2 library tibble library stringi set seed 1 df lt
  • django - 限制用户数量

    对不起我的英语不好 只有一个问题 是否有任何方法可以限制 Django 应用程序中可以创建的用户数量 我搜索了很多地方 只找到了这个 但我在仓库中看到最后一次更新是 3 年前https github com 1stvamp django l
  • 在 ASP.NET MVC 5 应用程序中启用 SSL 会导致 OpenIdConnectProtocolValidator 问题

    我有一个针对 Azure Active Directory 进行身份验证的 ASP NET MVC 5 应用程序 我想在整个应用程序上启用 SSL 因此利用全局过滤器如下 public class FilterConfig
  • 外键未存储在 Yii 中

    我有一个这样的数据库 Group id name Member id group id firstname lastname membersince Now as group id is foreign key then when I wi