【问题标题】:Laravel Model create function returns column with null valueLaravel 模型创建函数返回具有空值的列
【发布时间】:2016-02-04 01:18:00
【问题描述】:

在 Laravel 中,当我运行以下查询时,它会返回一个包含空值的行。

//Cards.php

public function __construct(array $attributes = []) {
    $this->gateway = StripeGateway;
} 


protected $fillable = ['user_id', 'card_id', 'customer_id', 'exp_year', 'exp_month', 'funding', 'brand', 'last4'];

public function createNewCardFromCustomer($user_id, $customer)
    {

        $result = $this->create([
            'user_id' => $user_id,
            'customer_id' => $customer->id,
            'card_id' => $customer['sources']['data'][0]->id,
            'exp_year' => $customer['sources']['data'][0]->exp_year,
            'exp_month' => $customer['sources']['data'][0]->exp_month,
            'funding' => $customer['sources']['data'][0]->funding,
            'brand' => $customer['sources']['data'][0]->brand,
            'last4' => $customer['sources']['data'][0]->last4
        ]);

        return $result;

    }

即使是模型静态创建方法也能接收到正确的参数。我也处理了集体作业。

【问题讨论】:

  • 那么createNewCardFromCustomer 是卡片模型中的一个方法吗?你到底是怎么调用这个方法的?在尝试给您回复之前,请确保我了解您的情况。
  • 是的,它是 Cards 模型中的一个函数。我叫它$card = (new Cards())->createNewCardFromCustomer($user->id, $customer);
  • dd($customer)检查你肯定传递了一些东西并且你的参考是正确的
  • 我已经检查过了,我得到了所有的值。另外,在这个模型的构造函数中,我有 $this->gateway = StripeGateway;这会影响什么吗?
  • 你能展示你的构造函数吗?

标签: laravel laravel-5.1


【解决方案1】:

我也在 Laracasts 上发布了这个:)

无论如何,您必须将构造函数更改为:

public function __construct(array $attributes = []) {
    $this->gateway = StripeGateway;
    parent::__construct($attributes);
}

您正在覆盖模型的基本构造函数,这会更改其默认行为。 Laravel 将构造函数用于很多事情(创建方法、关系等)。

基本模型的构造函数做了几件事,但其中一个非常重要的部分是它接受一个数组来填充其属性,如下所示:

public function __construct(array $attributes = [])
{
    $this->bootIfNotBooted();

    $this->syncOriginal();

    $this->fill($attributes);
}

因此,在设置网关属性后,您应该调用父级的构造函数并传递属性。

【讨论】:

  • 是的 :) 只是希望有人也在这里发布答案 :) 谢谢伙计。
猜你喜欢
  • 2012-08-18
  • 2020-06-11
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 2018-01-06
  • 1970-01-01
  • 1970-01-01
  • 2020-05-09
相关资源
最近更新 更多