【问题标题】:Laravel 4 - getting total from related tableLaravel 4 - 从相关表中获取总数
【发布时间】:2013-07-22 13:03:48
【问题描述】:

我有两张表,一张叫 invoice,另一张叫 invoice_products。 invoice 包含发票的基本信息,但没有总数。但是 invoice_products 包含附加到订单的实际项目。这使我可以通过添加新的 invoice_product 来自定义订单。总数是通过运行一个函数来完成的,该函数循环遍历附加的 invoice_products 并将它们相加。我想知道的是:

我可以使用 mutator 或其他一些技巧来生成 invoice->total 已经填充了它,而无需直接调用函数来完成

$invoice = Invoice::find(1);
echo $invoice->total;

我查看了访问器和修改器的文档,这似乎是我正在做的,但我在网上找不到任何实际操作与当前模型相关的表的示例。

谢谢。

【问题讨论】:

    标签: php laravel laravel-4 eloquent mutators


    【解决方案1】:

    只需在您的模型中添加一个新函数total()

    public function total()
    {
        // You can access the model using $this
        // example: $this->id
        // ...
        // Your logic to get the count
        // ...
    
        $this->total = $theGeneratedCount;
        return $this;
    }
    
    $invoice = find(1)->total(); // returns a Invoice model
    echo $invoice->total;
    

    这样你可以继续链接。否则,您可以只返回计数,但您将无法链接。

    ...
    return $theGeneratedCount;
    ...
    
    $invoice = find(1);
    echo $invoice->total(); // returns the count
    

    要让 $invoice->total 起作用,您需要指定一个 __get() 魔术方法:

    public function __get($name)
    {
        if(method_exists($this, $name) return $this->{$name}()
        return parent::__get($name);
    }
    

    【讨论】:

    • 这似乎有效,但我无法获得 $invoice->total 工作;只有 $invoice->total(),这很好,因为我不需要将它链接到任何地方。除非我必须将 ->total() 添加到查找的末尾?无论如何要避免这种情况?
    【解决方案2】:

    如果你想使用访问器,你可以在 Invoice 模型中定义一个方法

    public function getTotalAttribute()
    {
      // You can access the related model e.g if your invoice is related to a product model          
      //you can access the products collection by the relationship name
    
      $this->products->...
    
      // calculate the total ... 
    
       return $total;
    }
    

    然后你可以随意调用$invoice->total的方法,该属性将在$invoice对象中可用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-05
      • 1970-01-01
      • 2014-10-10
      • 2023-04-06
      • 1970-01-01
      • 2011-01-28
      相关资源
      最近更新 更多