O
O
Organizm7772019-03-29 21:38:35
Laravel
Organizm777, 2019-03-29 21:38:35

How to link models?

There is a table with users:

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();
        });

Table with servers:
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();
        });

Intermediate table server-user (many-to-many):
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();
        });

Table of purchased servers:
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();
        });

Essence:
the user can buy several servers. How to define relationships in models?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
javanub, 2019-03-30
@Organizm777

public function server()
{
return $this->belongsToMany('App\ServerModel', 'server_user', 'user_id', 'server_id');
}
In the user model, try adding this method, only specify your ServerModel

A
Alex Wells, 2019-03-29
@Alex_Wells

If server_user and purhcased_servers are not related to each other, then add user_id to purchased_servers and that's it, hasMany comes out.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question