【问题标题】:Object of class 'modelName' could not be converted to int in laravel类“modelName”的对象无法在 laravel 中转换为 int
【发布时间】:2018-10-27 11:08:05
【问题描述】:

我正在尝试创建一个发票编号,例如 - HCL/LF/02/2018,其中新发票的编号将加一。有人能帮我得到预期的invoice_no吗?我在我的控制器中尝试过这样的事情 -

public function create()
{
    $check = OrderProformaInvoice::orderBy('created_at', 'DESC')->get();
    $number = 01;
    $year   = date('Y');
    if (count($check) > 0) {

        $invoiceNo = OrderProformaInvoice::latest()->first(['invoice_no']);

        $arr     = array('HCL','LF', $invoiceNo + 1, $year);
        $newInvoiceNo = implode("/",$arr);
    }else{

        $arr     = array('HCL','LF', $number, $year);
        $newInvoiceNo = implode("/",$arr);

    }
    return view('admin.marchendaising.order-proforma-invoices.create', compact('newInvoiceNo'));
}

在我看来,表单输入字段是-

<input type="text" name="invoice_no" class="form-control" value="{{ $newInvoiceNo }}">

【问题讨论】:

  • 运行这段代码会得到什么?还有发票号码,因为您已经拨打了数据库电话以获取所有发票,您的$invoiceNo 可能只是count($check) + 1。在年份下,您可以写$numOfInvoices = count(check),然后拨打$numOfInvoices++。编辑:我刚刚注意到您甚至没有在创建功能中保存新发票,因此除非您保存它们,否则数字永远不会增加?
  • 你能转储$invoiceNo 吗?是对象还是整数?
  • 对于我之前的条目,我手动插入invoice_no字段HCL/LF/01/2018

标签: php mysql laravel explode implode


【解决方案1】:

你在这里犯了一个错误:

$invoiceNo = OrderProformaInvoice::latest()-&gt;first(['invoice_no']);

不需要这一行,因为您已经计算了所有 OrderProformaInvoice,因此我们也可以将其设置为一个变量,然后为新变量增加它,而不是再次调用数据库。

如果您要删除数据库记录,您可以使用

$invoice = OrderProfromaInvoice::orderBy('created_at', 'desc')-&gt;first();

然后,您可以使用 $invoice-&gt;id++ 代替 $numOfInvoices++,它将获取最新发票的 ID 并将其加一。

public function create()
{
    $check = OrderProformaInvoice::orderBy('created_at', 'DESC')->get();
    $year   = date('Y');
    $numOfInvoices = count($check)

    $arr = array('HCL','LF', $numOfInvoices++, $year);
    $newInvoiceNo = implode("/",$arr);


    // You could also just do this

    $newInvoiceNo = 'HCL/LF/' . $numOfInvoices++ . '/' . $year;
    // $newInvoiceNo will equal example: 'HCL/LF/12/2018';


    return view('admin.marchendaising.order-proforma-invoices.create', compact('newInvoiceNo'));
}

【讨论】:

  • 您遇到什么错误?这并不是说您的问题有错误。
  • 如果您仍然无法将 ModelName 转换为 int,那将来自此行:$arr = array('HCL','LF', $invoiceNo + 1, $year); 我假设 $invoiceNo 将是您的模型,dd($invoiceNo)var_dump($invoiceNo)并告诉我们这会给您带来什么。
  • 我已经更新了我的答案,删除了 if 语句,因为如果您只使用 $numOfInvoices 并每次都添加一个,那将毫无意义。你也可以使用DB::table('invoice_table')-&gt;count();,它会返回一个int。那么就不需要count($check)。你可以了解一下here by scrolling down to aggregates
【解决方案2】:

你在这行有错误:

$invoiceNo = OrderProformaInvoice::latest()->first(['invoice_no']);

正确:

$invoiceNo = OrderProformaInvoice::latest()->get()->invoice_no;

【讨论】:

  • 现在我得到 - Undefined property: Illuminate\Database\Eloquent\Builder::$invoice_no 错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-03
  • 1970-01-01
  • 2019-01-10
  • 1970-01-01
  • 2019-05-02
  • 2021-11-08
相关资源
最近更新 更多