Reputation: 185
I use Eloquent through the library illuminate/database, not Laravel.
I have an users table, a stripe_customer_ids table where I save the stripe customer id once Stripe generate it and a user_stripe_subscriptions table where I save the details about the subscriptions.
I need to retrieve the user's subscription id in the user_stripe_subscriptions table with the user's data in the users table.
I tried changing many options in foreign key and local key options following the Laravel documentation but the query still return an empty array.
This is the relationship I setted in the User model:
public function userStripeSubscription() {
return $this->hasManyThrough('\App\Models\UserStripeSubscription', '\App\Models\StripeCustomerId', 'user_id', 'stripe_customer_id', 'id', 'id');
}
In the StripeCustomerId model the relationship with the User model is setteb by:
public function user() {
return $this->belongsTo(User::class, "user_id", "id");
}
and the relationship with UserStripeSubscription is setted by:
public function userStripeSubscriptions() {
return $this->hasOne(UserStripeSubscription::class, 'stripe_customer_id', 'stripe_customer_id');
}
In the UserStripeSubscription model there is the relationship with the StripeCustomerId model:
public function stripeCustomerId() {
return $this->belongsTo(StripeCustomerId::class, "stripe_customer_id", "stripe_customer_id");
}
Obviously the table are correctly populated so I expect to get a result with this code:
$user = User::where('id', $userId)->with('userStripeSubscription')->first();
but I only get the user's array and an empty array like this:
["relations":protected]=>
array(1) {
["userStripeSubscription"]=>
object(Illuminate\Database\Eloquent\Collection)#40 (1) {
["items":protected]=>
array(0) {
}
}
}
Thanks in advance for your help!
Upvotes: 0
Views: 1090
Reputation: 25906
The second local key is incorrect:
public function userStripeSubscription()
{
return $this->hasManyThrough(
'\App\Models\UserStripeSubscription', '\App\Models\StripeCustomerId',
'user_id', 'stripe_customer_id',
'id', 'stripe_customer_id'
); ^^^^^^^^^^^^^^^^^^
}
Upvotes: 1