【发布时间】:2019-04-11 19:45:03
【问题描述】:
我有一个问题 - 是否可以在 laravel 中将属性从控制器传递或共享到模型。这是“问题”的一些代码示例。
基本上我有一个模型方法,它以给定货币获取产品价格。
class Product extends Model
{
public function getPrice()
{
return number_format($this->price_retail / $this->sessionHelper->getCurrentCurrency()->conversion_rate, 2);
}
}
sessionHelper 是一个单独的类,它提供有关当前货币的信息。我想删除这部分并使用控制器中的属性
在项目中,我的 productController 可以访问从 baseController 扩展的全局变量:
class ProductController extends BaseController
{
protected $product;
public function __construct(Product $product)
{
parent::__construct();
$this->product = $product;
$this->currentCurrency //gives current currency info which i need in model
}
//test function
public function showFirstProductPrice(){
$this->product->first()->getPrice();
}
}
我可以像这样通过函数传递变量:
$this->product->first()->getPrice($Variable);
但在视图中我每次都需要传递 $variable。目前我直接调用模型方法,它正在调用货币兑换率的助手并且它正在工作,但我想有更好的方法来做到这一点。
有人有什么想法吗?
【问题讨论】:
-
在
function getPrice()上获取价格需要传递对象并调用function -
有
appends,阅读this部分。