使用Laravel Cashier和多对多关系插入记录时出错

问题描述 投票:0回答:2

我在Laravel中的用户和订阅表之间存在多对多关系,如下所示:

在Subscription.php中:

public function users()
{
    return $this->belongsToMany('App\User')->withTimestamps();
}

在User.php中

public function subscriptions()
{
    return $this->belongsToMany('App\Subscription')->withTimestamps();
}

我在Cashier中创建了一个新订阅(使用Stripe),如下所示:

$user->newSubscription($planname, $planname)->create();

(请注意,产品和计划名称当前相同且用户的卡片已记录在案,因此缺少条带令牌。)

但是当我运行这个时,我收到一个错误:

SQLSTATE [HY000]:常规错误:1364字段'user_id'没有默认值(SQL:插入到subscriptionsnamestripe_idstripe_planquantityupdated_atcreated_at)值(projects,sub_EY1zRywZ1jUjLl,projects,1,2019) -02-17 20:07:36,2019-02-17 20:07:36))

我不确定这种关系是否导致问题,或者它是否是我的新订阅代码。我该如何解决这个错误?

更新:

我做了以下更改,但仍然遇到同样的错误:

$user->newSubscription($planname, $planname)->create(null,[
    'user_id' => $user->id, 
]);

更新2:

我做了以下更改,仍然发生完全相同的错误:

 $id = Auth::id();
 $user = User::find($id);

  // $user = Auth::user();
laravel many-to-many laravel-5.5 laravel-cashier
2个回答
0
投票

你有Billable特性添加到你的User模型?


0
投票
General error: 1364 Field 'user_id' doesn't have a default value. 

根据这个,我认为你需要通过$ id = Auth :: id();用id值填充user_id列;


Taken from laravel documentation:

其他用户详情

如果要指定其他客户详细信息,可以将它们作为第二个参数传递给create方法:

$user->newSubscription('main', 'monthly')->create($stripeToken, [
    'email' => $email, 
]);

UPDATE

你能试试这个:

 $id = Auth::id();
 $user = User::find($id);

 $user->newSubscription($planname, $planname)->create();
© www.soinside.com 2019 - 2024. All rights reserved.