使用查询生成器在Laravel中计算字段

时间:2017-03-30 15:49:07

标签: php laravel

我一直在Laravel项目中工作,我想知道如何在刀片视图中显示计算字段?我想从发票和总计算字段中检索一些信息。

我想得到这个结果,但是使用Eloquent 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

提前非常感谢你。

3 个答案:

答案 0 :(得分:2)

你可以使用laravels DB::raw(),它将字符串注入到查询中,如下所示:

Laravel raw expressions

InvoiceHeader::select('invoiceheader.id', 'invoiceheader.customerlastname',
   'invoiceheader.customerfirstname', 'invoiceheader.customernit', 
   'invoicedetail.productid', 'invoicedetail.quantity', 
   'invoicedetail.saleprice', DB::raw('(quantity * saleprice) as Total'))
->join('invoicedetail', 'invoiceheader.id', '=', 'invoicedetail.invoiceid')
->get();

注意:请务必在页面顶部导入use DB;

答案 1 :(得分:1)

您可以通过使用Eloquent关系和访问器来实现此目的。

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 docs中的文本:

  

要定义访问者,请在模型上创建getFooAttribute方法   其中Foo是您希望访问的列的“studly”套件名称。   在这个例子中,我们将为first_name定义一个访问器   属性。当Eloquent时,访问者将自动调用   尝试检索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
}

您可以阅读有关Accessors& amp ;;的更多信息。关于官方文件here的变种人。阅读有关雄辩关系的here

答案 2 :(得分:0)

试试这个

InvoiceHeader::join("invoicedetail",function($query){
    $query->on("invoiceheader.id", "=", "invoicedetail.invoiceid")
})
->select("invoiceheader.id", 
         "invoiceheader.customerlastname",
         "invoiceheader.customerfirstname", 
         "invoiceheader.customernit",
         "invoicedetail.productid", 
         "invoicedetail.quantity",
         "invoicedetail.saleprice", 
\DB::raw("(invoicedetail.quantity * invoicedetail.saleprice) as Total"))
->get();