@Organizm777

Как связать модели?

Есть таблица с юзерами:
Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

Таблица с серверами:
Schema::create('servers', function (Blueprint $table) {
            $table->increments('id')->unsigned();
            $table->string('ip')->unique();
            $table->string('login');
            $table->string('pass');
            $table->string('country')->nullable();
            $table->string('image_url')->nullable();
            $table->double('ping')->nullable();
            $table->integer('personalPrice');
            $table->integer('sharedPrice');
            $table->integer('uptime')->default(100);
            $table->timestamps();
        });

Промежуточная таблица server-user(многие-ко-многим):
Schema::create('server_user', function (Blueprint $table) {
            $table->increments('id')->unsigned();
            $table->integer('user_id')->unsigned()->onDelete('cascade');
            $table->integer('server_id')->unsigned()->onDelete('cascade');
            
            $table->timestamps();
        });

Таблица купленных серверов:
Schema::create('purchased_servers', function (Blueprint $table) {
            $table->increments('id')->unsigned();
            $table->date('purchase_date')->nullable();
            $table->date('payment_date')->nullable();
            $table->boolean('status');

            $table->integer('server_id')->unsigned();
            $table->foreign('server_id')->references('id')->on('server_user')->onDelete('cascade');

            $table->timestamps();
        });

Суть:
юзер может купить несколько серверов. Как определить связи в моделях?
  • Вопрос задан
  • 86 просмотров
Решения вопроса 1
@javanub
public function server()
{
return $this->belongsToMany('App\ServerModel', 'server_user', 'user_id', 'server_id');
}

В моделе юзера попробуйте добавьте этот метод, только ServerModel укажите свой
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
Alex_Wells
@Alex_Wells
PHP/Kotlin
Если server_user и purhcased_servers друг к другу не имеют отношения, то добавляете в purchased_servers user_id и все, выходит hasMany.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы