在eloquent集合中从对象获取嵌套值

时间:2018-02-06 17:19:09

标签: php laravel object eloquent

我使用laravel的收银台和条纹& amp;来自Invoices的集合,我试图通过其subscription密钥检索特定的发票:

Collection {#157 ▼
  #items: array:1 [▼
    0 => Invoice {#162 ▼
      #owner: User {#163 ▶}
      #invoice: Invoice {#208 ▼
        +"id": "in_1BsZF2F3eLup6dYnvs74ij6B"
        +"object": "invoice"
        ...
        +"statement_descriptor": null
        +"subscription": "sub_CH7UxbgcTCeHLp"
        +"subtotal": 1999
        +"tax": null
        +"tax_percent": null
        +"total": 1999
        +"webhooks_delivered_at": 1517934260
      }
    }
  ]
}

以下是user模型用于检索其Invoices的此集合的函数:

public function invoices($includePending = false, $parameters = [])
{
    $invoices = [];

    $parameters = array_merge(['limit' => 24], $parameters);

    $stripeInvoices = $this->asStripeCustomer()->invoices($parameters);

    // Here we will loop through the Stripe invoices and create our own custom Invoice
    // instances that have more helper methods and are generally more convenient to
    // work with than the plain Stripe objects are. Then, we'll return the array.
    if (! is_null($stripeInvoices)) {
        foreach ($stripeInvoices->data as $invoice) {
            if ($invoice->paid || $includePending) {
                $invoices[] = new Invoice($this, $invoice);
            }
        }
    }

    return new Collection($invoices);
}

每个Invoice对象都有两个属性,Owner(当前用户)和实际Invoice

深入了解每个Invoices subscription密钥并检查该值的正确语法是什么?

我尝试了以下查询,结果是NULL

$user->invoices()->where('subscription','sub_CH7UxbgcTCeHLp')->first();

更新

当我转储以下查询$user->invoices()->first()->subscription时,它会在sub_CH7UxbgcTCeHLp中返回正确的字符串,但是当我尝试使用$user->invoices()->firstWhere('subscription', 'sub_CH7UxbgcTCeHLp')对其进行检查时,其结果为NULL

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

$id = 'sub_CH7UxbgcTCeHLp'
$user->invoices->first(function ($invoice) use ($id) {
    return $invoice->invoice->subscription === $id;
});

在您尝试使用where时,您似乎错过了实际发票对象上的嵌套发票属性。这可能有效:

$id = 'sub_CH7UxbgcTCeHLp';
$user->invoices()->where(function ($query) use ($id) {
    $query->where('invoice.subscription', $id);
})->first();