简体   繁体   English

如何在Yii中将变量从一种模型传递到另一种模型?

[英]How do I pass a variable from one model to another in Yii?

I have this code which is inside a view Inventory.php from a model named Inventory. 我有此代码,该代码位于名为Inventory的模型的View Inventory.php中。 This is used to display the current ID being viewed: 这用于显示当前正在查看的ID:

<?php $inventoryID = $model->inventory_id; ?> <--- this one.

<h3>View Info for Inventory No. <?php echo $inventoryID; ?>: <?php echo $model->brand->brand; ?> <?php echo $model->model;?></h3>

I want to use it in another model named InventoryHistory because it will be saved in the InventoryHistory database. 我想在另一个名为InventoryHistory的模型中使用它,因为它将被保存在InventoryHistory数据库中。 How do I do that? 我怎么做?

You are not approaching this correctly. 您未正确处理此问题。 You should not think in terms of "how do I use this same ID in another model" after you have already created the database schema and models and you've even created the views! 在创建数据库模式和模型,甚至创建视图之后,您就不要以“如何在另一个模型中使用相同的ID”的方式思考问题! You should define these relationships on the database level and then map them to models with the correct relations between them. 您应该在数据库级别定义这些关系,然后将它们映射到具有正确关系的模型。 Then, you will have everything you need available to you and you will know how to get this ID in the other model. 然后,您将拥有所需的一切,并且您将知道如何在其他模型中获取此ID。 Here's a useful link to get you started - http://www.yiiframework.com/doc/guide/1.1/en/database.arr 这是帮助您入门的有用链接-http: //www.yiiframework.com/doc/guide/1.1/en/database.arr

Assuming inventoryID is the PK of InventoryHistory, 假设ventoryID是InventoryHistory的PK,

$inventoryID = $model->inventory_id;
$history = InventoryHistory::model()->findByPk($inventoryID);

Samuel's approach is correct, but if you want carry any type of variable inside whole app, you can use global varables with setState and getState, you also check varable with hasState. 塞缪尔(Samuel)的方法是正确的,但是如果您想在整个应用程序中携带任何类型的变量,则可以将全局变量与setState和getState一起使用,还可以对hasState进行检查。 In Yii 1. Yii::app()->user->setState('key','value'); 在Yii 1中。Yii :: app()-> user-> setState('key','value'); Yii::app()->user->getState('key'); YII ::应用程序() - >用户>的getState( '钥匙'); To unset: Yii::app()->user->setState('key',null); 取消设置:Yii :: app()-> user-> setState('key',null);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM