【问题标题】:Share controller property to model method - laravel将控制器属性共享给模型方法 - laravel
【发布时间】: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部分。

标签: php laravel eloquent


【解决方案1】:

当然你可以传递一个变量。

    class Product extends Model
   {
    public function getPrice($variable)
        {
            return number_format($this->price_retail /$variable, 2);
        }
    }

在你的控制器中你可以做到这一点

    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($variable);
   }
}

【讨论】:

  • 是的,但是每次我调用这个函数时都必须传递 $variable。因此,如果我使用 $products = $this->product->limit(30)->get() 并将其发送到视图,我还需要发送 $conversion_rate 变量,因为我需要为每个产品调用 getPrice这个 $product->getPrice($conversion_rate)。我正在寻找一些干净的解决方案,我不需要额外的变量传递来查看。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-16
  • 1970-01-01
  • 2017-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-16
相关资源
最近更新 更多