【发布时间】:2019-07-11 12:46:18
【问题描述】:
我通过库照明/数据库使用 Eloquent,而不是 Laravel。
我有一个 users 表,一个 stripe_customer_ids 表,我在 Stripe 生成它后保存条带客户 ID,还有一个 user_stripe_subscriptions 表,我保存有关订阅的详细信息。
我需要在 user_stripe_subscriptions 表中使用用户表中的用户数据检索用户的订阅 ID。
我尝试按照 Laravel 文档更改外键和本地键选项中的许多选项,但查询仍然返回一个空数组。
这是我在 User 模型中设置的关系:
public function userStripeSubscription() {
return $this->hasManyThrough('\App\Models\UserStripeSubscription', '\App\Models\StripeCustomerId', 'user_id', 'stripe_customer_id', 'id', 'id');
}
在 StripeCustomerId 模型中,与 User 模型的关系通过以下方式设置:
public function user() {
return $this->belongsTo(User::class, "user_id", "id");
}
并且与 UserStripeSubscription 的关系设置为:
public function userStripeSubscriptions() {
return $this->hasOne(UserStripeSubscription::class, 'stripe_customer_id', 'stripe_customer_id');
}
在 UserStripeSubscription 模型中存在与 StripeCustomerId 模型的关系:
public function stripeCustomerId() {
return $this->belongsTo(StripeCustomerId::class, "stripe_customer_id", "stripe_customer_id");
}
显然,表格已正确填充,因此我希望使用以下代码得到结果:
$user = User::where('id', $userId)->with('userStripeSubscription')->first();
但我只得到用户的数组和一个像这样的空数组:
["relations":protected]=>
array(1) {
["userStripeSubscription"]=>
object(Illuminate\Database\Eloquent\Collection)#40 (1) {
["items":protected]=>
array(0) {
}
}
}
提前感谢您的帮助!
【问题讨论】:
标签: php eloquent foreign-keys relationship