【问题标题】:get nested value from object in eloquent collection从 eloquent 集合中的对象获取嵌套值
【发布时间】:2018-02-06 17:19:08
【问题描述】:

我将 laravel 的收银员与 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

【问题讨论】:

    标签: php laravel object eloquent


    【解决方案1】:

    尝试以下方法:

    $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();
    

    【讨论】:

    • 我得到了很多 php warnings : Missing argument 2 for Illuminate\Support\Collection::where() ,`缺少 Illuminate\Support\Collection::operatorForWhere() 的参数 2` ,Undefined variable: operator PHP Warning: explode() expects parameter 2 to be string, object given
    猜你喜欢
    • 2021-08-20
    • 2019-07-25
    • 1970-01-01
    • 2014-02-23
    • 1970-01-01
    • 1970-01-01
    • 2013-10-11
    • 2021-11-29
    • 1970-01-01
    相关资源
    最近更新 更多