Laravel Таблица запросов с 3 отношениями - PullRequest
0 голосов
/ 26 февраля 2020

Буду заранее признателен за помощь в решении следующей проблемы, которую я не могу решить.

У меня есть 3 таблицы

Contracts
Currencies
Amounts

и сводная таблица

contract_currency_amount

Здесь я покажу вам миграции

Контракты

<?php

use Carbon\Carbon;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateContractsTable extends Migration
{
    /**
     * Contracts Table
     *
     * @var string
     */
    private $table = 'contracts';

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create($this->table, function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('number')->unique();
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists($this->table);
    }
}

Валюты

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCurrenciesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('currencies', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('abbreviation');
            $table->string('description');
            $table->boolean('active')->default(true);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('currencies');
    }
}

Суммы

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateAmountsTable extends Migration
{
    /**
     * Amounts Table
     *
     * @var string
     */
    private $table = 'amounts';

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create($this->table, function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->float('amount');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists($this->table);
    }
}

Сводная таблица Contract_Currency_Amount

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateContractCurrencyAmountTable extends Migration
{
    /**
     * Pivot Table
     *
     * @var string
     */
    private $table = 'contract_currency_amount';

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create($this->table, function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedInteger('contract_id');
            $table->unsignedInteger('currency_id');
            $table->unsignedInteger('amount_id');
            $table->timestamps();

            $table->foreign('contract_id')
                ->references('id')->on('contracts')
                ->onDelete('cascade');

            $table->foreign('currency_id')
                ->references('id')->on('currencies')
                ->onDelete('cascade');

            $table->foreign('amount_id')
                ->references('id')->on('amounts')
                ->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists($this->table);
    }
}

Я создал модели для каждой из этих таблиц, включая модель для сводная таблица, но я не знаю, как сделать запрос к сводной таблице, чтобы она возвращала все данные определенной записи c, относящейся к 3 таблицам. например, я хочу, чтобы в представлении с Blade go через переменную отображались все суммы определенного c контракта и возможность go через эту переменную следующим образом:

@foreach($amounts as $amount)
    {{ $amount->currency->abbreviation }}
@endforeach

Я имею в виду, я хочу, чтобы запрос возвращал связанные значения 3 таблиц. У меня нет опыта использования сводных таблиц, я был бы признателен за любую помощь ..

РЕДАКТИРОВАТЬ 1

Сумма Модель

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Amount extends Model
{
    /**
     * Attributes that should be mass-assignable.
     *
     * @var array
     */
    protected $fillable = ['amount'];
}

Модель валюты

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * Class Currency
 *
 * @property $id
 * @property $abbreviation
 * @property $description
 * @property $active
 * @property $created_at
 * @property $updated_at
 *
 * @package App
 * @mixin \Illuminate\Database\Eloquent\Builder
 */
class Currency extends Model
{
    /**
     * Attributes that should be mass-assignable.
     *
     * @var array
     */
    protected $fillable = ['abbreviation','description','active'];
}

Модель контракта

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\Entity;
use App\Models\CInitiative;

class Contract extends Model
{
    // TODO: This!
}

Модель ContractCurrencyAmount

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Relations\Pivot;

class ContractCurrencyAmount extends Pivot
{
    protected $table = 'contract_currency_amount';
}

1 Ответ

0 голосов
/ 26 февраля 2020

Чтобы достичь того, что вы ищете, вы должны правильно настроить свои модели. Вы должны настроить свою модель ContractCurrencyAmount, чтобы она была обычной красноречивой моделью, а не расширяющей сводкой.

ContractCurrencyAmount

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ContractCurrencyAmount extends Model
{
    protected $table = 'contract_currency_amount';

    public function contract()
    {
        return $this->belongsTo('App\Contract');
    }

    public function currency()
    {
        return $this->belongsTo('App\Currency');
    }

    public function amount()
    {
        return $this->belongsTo('App\Amount');
    }
}

Контракт

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Contract extends Model
{
    public function relations()
    {
        return $this->hasMany('App\ContractCurrencyAmount', 'contract_id');
    }
}

Валюта

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Currency extends Model
{
    public function relations()
    {
        return $this->hasMany('App\ContractCurrencyAmount', 'currency_id');
    }
}

Сумма

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Currency extends Model
{
    public function relations()
    {
        return $this->hasMany('App\ContractCurrencyAmount', 'amount_id');
    }
}

Тогда вы можете сделать это:

foreach($amounts as $amount) {
{
    foreach($amount->relations as $relation) {
        $relation->currency->abbreviation;
    }
}

Вы также можете использовать энергичную загрузку для оптимизации запросов к базе данных:

$amounts = Amount::with('relations.currency')->get();

Это позволит предварительно загрузить все данные, которые вам нужны в вышеуказанных циклах for, вместо того, чтобы запрашивать базу данных на каждой итерации.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...