多个hasMany关系如何通过eloquent获取数据

How to get data through eloquent with multiple hasMany relations

我有以下表格:

users

| id | name  |
--------------
| 1  | user1 |
| 2  | user2 |

countries

| id  | name        |
---------------------
| 1   | Netherlands |
| 2   | Germany     |
| 3   | Belgium     |

vat_numbers

| id  | user_id | country_id | number |
---------------------------------------
| 1   | 1       | 1          | 12345
| 2   | 1       | 2          | 54321
| 3   | 2       | 1          | 12342
| 4   | 2       | 3          | 13532

型号:

User.php

public function vatNumbers(): HasMany
{
    return $this->hasMany(VatNumber::class);
}

Country.php:

public function vatNumbers(): HasMany
{
    return $this->hasMany(VatNumber::class);
}

VatNumber.php:

public function user(): BelongsTo
{
    return $this->belongsTo(User::class);
}

public function country(): BelongsTo
{
    return $this->belongsTo(Country::class);
}

我希望用户能够为每个国家/地区创建增值税号。我有一个包含多个表单的 blade 文件,每个表单对应一个国家/地区:

_form.blade.php

<form method="POST" action="{{ route('users.vat-numbers.store', ['id' => $user->id]) }}">
    @csrf
    <div>
        <label>
            <span>{{ $country->name }}</span>
        </label>
        <div class="col-md-9">
            <button type="button" class="{{ country has vat ? 'd-none' : '' }}">Add VAT Number</button>
            <input type="text" class="{{ country has vat ? '' : 'd-none' }}" name="number">
        </div>
    </div>
</form>
@foreach($countries as $country)
    @include('_form', ['user' => $user, 'country' => $country])
@endforeach

如何获得正确的关系来检查用户是否已经拥有给定国家/地区的增值税号?

您可以在检索国家列表时使用 filtered with

$userId = auth()->id();
$countries = Country::with(['vatNumbers' => function($vatQuery) use ($userId) {
        $vatQuery->where('user_id', $userId);
    })->get();

当您在 blade 中签入关系 vatNumbers 时,如果它是空的 collection,则没有输入该国家/地区的增值税。