CakePHP - 访问 beforeSave 中的关联模型
在我的应用程序中,报价属于一种产品,而该产品又属于一种材料。由于我无法在从 Quote 模型访问产品模型 afterFind 数组时包含该材料,因此我已将 Quote 直接与材料相关联。
我现在遇到的问题是,报价的material_id需要根据为报价选择的产品自动保存
,即从所选产品中提取Product.material_id的值并将其保存到Quote.material_id字段在报价保存到数据库之前自动进行。
我对 cakePHP 很陌生。有谁知道如何做到这一点?
编辑:
这是一个帮助解释的示例。在我的报价模型中,我可以:
public function beforeSave($options) {
$this->data['Quote']['material_id'] = 4;
return true;
}
但我需要做更多类似这样的事情,但这是行不通的:
public function beforeSave($options) {
$this->data['Quote']['material_id'] = $this->Product['material_id'];
return true;
}
In my app Quotes belongTo a product, which in turn belongs to a material. As I can't get the product model afterFind array to include the material when it is accessed from the Quote model I have associated the Quote directly with a material.
The problem I'm having now is that the material_id for the quote needs to be automatically saved based on the product which is selected for the quote
i.e. pulling the value of Product.material_id from the selected product and saving it to the Quote.material_id field automatically before the Quote has been saved to the database.
I'm quite new to cakePHP. Does anyone know how this can be done?
EDIT:
Here is an example to help explain. In my Quote model i can have:
public function beforeSave($options) {
$this->data['Quote']['material_id'] = 4;
return true;
}
but i need to do something more like this which doesn't work:
public function beforeSave($options) {
$this->data['Quote']['material_id'] = $this->Product['material_id'];
return true;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我很震惊这个问题还没有得到正确的回答……
Oldskool 的回答是半正确的,但并不完全正确。 “$this->Quote”的使用是不正确的,因为 beforeSave 函数本身位于 Quote 类中。我将用一个例子来解释。
->我们有一个模型订阅,它属于一个订阅计划
->模型 SubscriptionsPlan hasMany Suscriptions
在 beforeSave 函数中访问 SubscriptionsPlan 数据订阅模型,您将执行以下操作:
I'm shocked this hasn't been properly answered yet....
Oldskool's response is semi-correct, but not entirely right. The use of "$this->Quote" is incorrect, as the beforeSave function itself resides in the Quote class. I'll explain using an example.
-> We have a model Subscription which belongsTo a SubscriptionsPlan
-> Model SubscriptionsPlan hasMany Suscriptions
To access the SubscriptionsPlan data in a beforeSave function in the Subscription model, you would do the following:
它可能应该通过使用 find 来工作。
It should probably work by using a find instead.