【问题标题】:Convert a collection into an Eloquent object将集合转换为 Eloquent 对象
【发布时间】:2016-06-23 09:09:26
【问题描述】:

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

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

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

如果我做一个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' => 

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

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

查看 Laravel 的文档,假设我可以使用 collect 转换为集合:

    $collection = collect($invoices);

$collection 没有解决问题。现在数据结构不同但仍然不能使用 Eloquent。现在的数据是:

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

但显示数据是Illuminate\Support\Collection,似乎是正确的。

谢谢!

【问题讨论】:

    标签: php laravel-5 eloquent method-chaining xero-api


    【解决方案1】:

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

    $entity = $collection->first();
    

    You can find more information here关于Illuminate\Support\Collection有哪些可用的方法。

    【讨论】:

    • 谢谢!但仍然无法正常工作...做:$collection = collect($invoices); var_dump($collection->first()->where('Status','DRAFT')); 引发错误:Call to undefined method XeroPHP\Models\Accounting\Invoice::where()
    • 为什么要在实体上使用where()Model 不是查询生成器。如果要将模型用作查询构建器,则需要使用 first()->query()->where()->get()
    猜你喜欢
    • 1970-01-01
    • 2015-09-24
    • 1970-01-01
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    • 2017-06-30
    • 2019-08-17
    • 1970-01-01
    相关资源
    最近更新 更多