将集合转换为 Eloquent 对象

Jos*_*oss 1 php method-chaining eloquent laravel-5 xero-api

目前我在 Laravel 5.2 中使用 Xero API。我想利用 Eloquent 的强大功能来处理这些数据。

实际上,我可以恢复发票,甚至使用链接方法过滤它们,如下所示:

    $invoices = XeroPrivate::load('Accounting\\Invoice')
        ->where('Status', 'DRAFT')
        ->execute();
Run Code Online (Sandbox Code Playgroud)

如果我执行 a var_dump,我会得到这种数据:

object(XeroPHP\Remote\Collection)[173]
  public 0 => 
    object(XeroPHP\Models\Accounting\Invoice)[171]
      protected '_data' => 
        array (size=31)
          'Type' => string 'ACCPAY' (length=6)
          'Contact' => 
Run Code Online (Sandbox Code Playgroud)

雄辩的链接方法可以让我执行这样的事情。目前失败了:

    $invoices = XeroPrivate::load('Accounting\\Invoice')
        ->where('Date','>','2016-03-20')
        ->execute();
Run Code Online (Sandbox Code Playgroud)

检查 Laravel 的文档,假设我可以使用以下命令转换为集合collect

    $collection = collect($invoices);
Run Code Online (Sandbox Code Playgroud)

$collection并不能解决问题。现在数据结构不同了但仍然无法使用Eloquent。现在数据是:

object(Illuminate\Support\Collection)[163]
  protected 'items' => 
    array (size=24)
      0 => 
        object(XeroPHP\Models\Accounting\Invoice)[171]
          protected '_data' => 
            array (size=31)
Run Code Online (Sandbox Code Playgroud)

但事实证明,数据是Illuminate\Support\Collection正确的。

谢谢!

Gia*_*mPy 5

您可以使用方法获取集合中的单个项目first()

$entity = $collection->first();
Run Code Online (Sandbox Code Playgroud)

您可以在此处找到有关可用方法的更多信息Illuminate\Support\Collection

  • 为什么在实体上使用“where()”?“模型”不是查询生成器。如果你想使用模型作为查询构建器,你需要使用“first()->query()->where()->get()”。 (2认同)