我在使用 Staidenmeir 的 BelongsToThrough 包时遇到问题。这是我的 Laravel 11 项目中的内容:
数据库:
* ----------------------- *
| users |
* ----------------------- *
| + id |
| + address_id |
* ----------------------- *
* ----------------------- *
| addresses |
* ----------------------- *
| + id |
| + country_code_id |
* ----------------------- *
* ----------------------- *
| country_codes |
* ----------------------- *
| + id |
* ----------------------- *
用户.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);
}
}
地址.php
class Address extends Model
{
public function user(): HasOne
{
return $this->hasOne(User::class);
}
public function country_code(): BelongsTo
{
return $this->belongsTo(CountryCode::class);
}
}
国家/地区代码.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);
}
}
用户控制器.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');
}
}
我可以毫无问题地查询:
UserResource->load('address')
AddressResource->load('country_code')
CountryCodeResource->load('address')
AddressResource->load('user')
AddressResource->load('users')
与 hasManyThrough()现在问题:
如果我尝试由Staudenmeir提供的hasManyThrough、belongsToThrough(使用
UserResource->load('country_code')
)的逆操作,我总是收到以下错误消息:
"message": "Call to undefined relationship [country_code] on model [App\\Models\\User]."
我的代码有什么问题或者我误解了什么吗?在我看来,所有必要的关系都应该被定义,甚至 hasManyThrough 也能发挥作用。
如果您需要任何进一步的信息,请询问。
提前感谢您的帮助!
编辑
我也尝试过使用 camelCase 命名,但并没有解决问题。
为什么不像这样使用
hasOneThrough
:document
public function carOwner(): HasOneThrough
{
return $this->hasOneThrough(Owner::class, Car::class);
}