Как выбрать модели, которые имеют связь с другой моделью?

Как правильно настроить отношение многие ко многим между моделями Waste и WasteComponent в Laravel версии 8.0, используя таблицу, которая связывает их?
  • 23 августа 2024 г. 6:53
Ответы на вопрос 4
Чтобы выбрать модели, которые имеют связь с другой моделью в Laravel, вы можете использовать методы отношений Eloquent. Например, если у вас есть модели Waste и WasteComponent, которые имеют отношение многие ко многим через промежуточную таблицу, вы можете определить это отношение в каждой модели.

Для настройки отношения многие ко многим между моделями Waste и WasteComponent в Laravel версии 8.0 с использованием промежуточной таблицы, создайте модели Waste и WasteComponent, определите их отношения внутри модели:

```php
// Waste.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Waste extends Model
{
    public function wasteComponents()
    {
        return $this->belongsToMany(WasteComponent::class, 'waste_waste_component');
    }
}
```

```php
// WasteComponent.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class WasteComponent extends Model
{
    public function wastes()
    {
        return $this->belongsToMany(Waste::class, 'waste_waste_component');
    }
}
```

Затем в вашем контроллере или другом месте вы можете обращаться к этим отношениям для получения связанных моделей:

```php
$waste = Waste::find(1);
$wasteComponents = $waste->wasteComponents;
```

Теперь у вас есть способ выбрать модели WasteComponent, которые связаны с конкретным Waste.

Помните, что при работе с отношениями многие ко многим в Laravel, вам необходимо также создать и миграции для промежуточной таблицы, связывающей модели, и определить название этой таблицы во всех соответствующих отношениях.
<blockquote>If you need even more power, you may use the whereHas and orWhereHas methods to define additional query constraints on your has queries, such as inspecting the content of a comment:<br/>
<br/>
<pre><code class="php">use Illuminate\Database\Eloquent\Builder;
 
// Retrieve posts with at least one comment containing words like code%...
$posts = Post::whereHas('comments', function (Builder $query) {
    $query-&gt;where('content', 'like', 'code%');
})-&gt;get();
 
// Retrieve posts with at least ten comments containing words like code%...
$posts = Post::whereHas('comments', function (Builder $query) {
    $query-&gt;where('content', 'like', 'code%');
}, '&gt;=', 10)-&gt;get();</code></pre></blockquote> <a href="https://laravel.com/docs/11.x/eloquent-relationships#querying-relationship-existence" rel="nofollow">https://laravel.com/docs/11.x/eloquent-relationshi...</a>
<pre><code class="php">$wastes = Waste::whereHas('components', function ($query) {
    $query-&gt;whereIn('waste_component_id', [1, 2, 3]);
})-&gt;get();</code></pre>
<pre><code class="php">Waste::whereHas('components', static fn($q) =&gt; $q-&gt;whereIn('id', [1,2,3]))</code></pre>
Похожие вопросы