I have a problem using Staudenmeir's BelongsToThrough package. This is what I have in my Laravel 11 project:
Database:
* ----------------------- *
| users |
* ----------------------- *
| + id |
| + address_id |
* ----------------------- *
* ----------------------- *
| addresses |
* ----------------------- *
| + id |
| + country_code_id |
* ----------------------- *
* ----------------------- *
| country_codes |
* ----------------------- *
| + id |
* ----------------------- *
User.php
class User extends Model
{
public function address(): BelongsTo
{
return $this->belongsTo(Address::class);
}
public function country_code(): BelongsToThrough
{
return $this->belongsToThrough(CountryCode::class, Address::class);
}
}
Address.php
class Address extends Model
{
public function user(): HasOne
{
return $this->hasOne(User::class);
}
public function country_code(): BelongsTo
{
return $this->belongsTo(CountryCode::class);
}
}
CountryCode.php
class CountryCode extends Model
{
public function address(): HasMany
{
return $this->hasMany(Address::class);
}
public function users(): HasManyThrough
{
return $this->hasManyThrough(User::class, Address::class);
}
}
UserController.php
class UserController extends Controller
{
public function show(Request $request, User $user)
{
# access countryCode through address from user
# not working:
return (new UserResource($user))->load('country_code');
}
}
CountryCodeController.php
class CountryCodeController extends Controller
{
public function show(Request $request, CountryCode $countryCode)
{
# access user through address from countryCode
# working:
return (new CountryCodeResource($countryCode))->load('user');
}
}
I can query without problems:
UserResource->load('address')AddressResource->load('country_code')CountryCodeResource->load('address')AddressResource->load('user')AddressResource->load('users')with hasManyThrough()
Now the problem:
If i try the inverse of the hasManyThrough, belongsToThrough provided by Staudenmeir (using UserResource->load('country_code')), I always get the the following error message:
"message": "Call to undefined relationship [country_code] on model [App\\Models\\User]."
Is there any problem in my code or have i misunderstood something? In my opinion all necessary relations should be defined and even the hasManyThrough works like a charm.
If you need any further information, just ask.
Thanks for your help in advance!
Edit
I also tried it with camelCase naming, but it did not fix the problem.
why not use
hasOneThroughlike this: document