我一直在一个Laravel项目中工作,我想知道如何在刀片视图中显示一个计算出的字段?我想从发票和总计计算字段中检索一些信息。
我想得到这个结果,但使用雄辩的ORM。查询如下:
SELECT 
    invoiceheader.id, 
    invoiceheader.customerlastname,
    invoiceheader.customerfirstname, 
    invoiceheader.customernit,
    invoicedetail.productid, 
    invoicedetail.quantity,
    invoicedetail.saleprice, 
    (quantity * saleprice) as Total
FROM invoiceheader 
INNER JOIN invoicedetail
    ON invoiceheader.id = invoicedetail.invoiceid提前谢谢你。
发布于 2017-03-30 17:17:47
你可以通过说出雄辩的关系和访问者来做到这一点。
在您的InvoiceHeader模型中:
/*
Relation with the invoicedetail table
 */
public function detail()
{
    return $this->hasOne(InvoiceDetail::class, 'invoiceid', 'id');
}在您的InvoiceDetail模型中:
/*
The accessor field
 */
protected $appends = ['total_price'];
/*
Accessor for the total price
 */
public function getTotalPriceAttribute()
{
    return $this->quantity * $this->saleprice;
}要从方法名称中理解创建的访问器名称,下面是laravel文档中的文本:
要定义访问器,请在模型上创建一个getFooAttribute方法,其中Foo是要访问的列的“学习”大小写名称。在本例中,我们将为first_name属性定义一个访问器。当试图检索first_name属性的值时,访问器将被雄辩者自动调用:
对于您的查询,您可以:
// get all invoices in descending order of creation
$invoices = InvoiceHeader::recent()->get();
// loop invoice data to get the desired fields
foreach ($invoices as $invoice) {
    $customerfirstname = $invoice->customerfirstname;
    $totalprice = $invoice->detail->total_price;
    // more code
}https://stackoverflow.com/questions/43122595
复制相似问题