Php Laravel 4-从相关表格中获取总计
我有两张桌子,一张叫做发票,另一张叫做发票产品。发票包含发票的基本信息,但不包含总额。然而,invoice_products保留订单所附的实际项目。这使我可以通过添加新的发票产品来定制订单。总计是通过运行一个函数来完成的,该函数通过附加的invoice_产品循环并将它们相加。我想知道的是: 我是否可以使用一个mutator或其他一些技巧让invoice->total已经填充了它,而不直接调用函数来填充它Php Laravel 4-从相关表格中获取总计,php,laravel,laravel-4,eloquent,mutators,Php,Laravel,Laravel 4,Eloquent,Mutators,我有两张桌子,一张叫做发票,另一张叫做发票产品。发票包含发票的基本信息,但不包含总额。然而,invoice_products保留订单所附的实际项目。这使我可以通过添加新的发票产品来定制订单。总计是通过运行一个函数来完成的,该函数通过附加的invoice_产品循环并将它们相加。我想知道的是: 我是否可以使用一个mutator或其他一些技巧让invoice->total已经填充了它,而不直接调用函数来填充它 $invoice = Invoice::find(1); echo $invoice->
$invoice = Invoice::find(1);
echo $invoice->total;
我查看了访问器和变异器的文档,这似乎是我正在做的,但我在网上找不到任何实际操作与当前模型相关的表的示例
谢谢。只需在您的模型中添加一个新函数
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正常工作,您需要指定一个_uget()魔术方法:
public function __get($name)
{
if(method_exists($this, $name) return $this->{$name}()
return parent::__get($name);
}
如果要使用存取器,可以在
发票
模型中定义方法
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
对象中可用 这似乎工作,除了我不能得到$invoice->total工作;只有$invoice->total(),这很好,因为我不需要将它链接到任何地方。除非我必须将->total()添加到查找的末尾?为了避免这种情况?