【问题标题】:action Update() in Yii to update another model's updateYii 中的 action Update() 来更新另一个模型的更新
【发布时间】:2012-02-14 12:15:20
【问题描述】:

我有这样的数据库

 === Invoice ===
 id
 customer_id (FK)
 description

 === Customer ===
 id
 firstname
 lastname

我对这两种表单都有多模型,以便将 Cstomer 表加载到 Invoice 中。这样我就可以从一个视图轻松访问这两个模型。为此,我在这两个模型中都建立了关系,就像这样 Invoice模型中的realtion是这样的

  public function relations()
  {
    return array(
    'customer'    =>  array(self::BELONGS_TO,'Customer','customer_id'),
    );
  }

在客户模型中,关系是这样的

public function relations()
  {
    return array(
      'invoice' => array(self::HAS_MANY, 'Invoices','customer_id')
    );
  }

一切正常。但是当我在 Invoice 控制器文件中执行 actionUpdate() 时,没有定义 Customer 模型。所以我把它定义成这样

 public function actionView($id)
  {
    $this->render('view',array(
      'model'=>$this->loadModel($id),
      'customers'=>Customers::model()->findByPk(array('customer_id'=>$_GET['id']));
    ));
  }

它显示为未定义的偏移量:0。我希望在 ('customer_id'=>$_GET['id']) 中显示 id 的值,以便我可以轻松地显示和更新每个 id 的值。 如果我给出这样的值

public function actionView($id)
  {
    $this->render('view',array(
      'model'=>$this->loadModel($id),
      'customers'=>Customers::model()->findByPk(28);
    ));
  }

它很容易显示来自客户 ID 的价值。那么如何获得这些值呢?任何帮助和建议都将非常有用。

【问题讨论】:

    标签: mysql yii relational-database


    【解决方案1】:

    试试这个

    public function actionView($id)
      {
        $model = $this->loadModel($id);
        $this->render('view',array(
          'model'=>$model,
          'customers'=>Customers::model()->findByPk($model->customer_id);
        ));
      }
    

    【讨论】:

    • 谢谢@mazzucci 这么快的回复。那是行不通的。正如你在上面看到的数据库客户表在发票表中有一个外键。所以这就是我放一个数组的原因。在数组中,条件应该是什么,以便它在 Invoice 表和 Customer 表中具有相同的 id,或者类似 findByAttributes...
    • 那么你应该使用findAll方法而不是findByPk。也许这会更有帮助yiiframework.com/forum/index.php/topic/…
    • 那你觉得应该是什么条件呢?
    • 试试这个'customers'=>Customers::model()->findAll(array('customer_id'=>$_GET['id']))
    • 其实没有。客户表没有 customer_id 字段。您应该从发票中获取自定义的 id,然后通过 pk 客户搜索。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多