简体   繁体   中英

How to properly create a relationship two foreign keys referencing same table in Laravel Eloquent?

I've created relationshiop as below in the code. In 'tickets' table I use two foreign keys referring to 'users' table. When I use operator nad creator methods from Ticket model it works fine. But when I want to get ownerTickets or operatorTickets from User model i get null. I am not sure if I called these methods correctly.

My database is well filled, I see that user is either owner or operator.

class CreateTicketsTable extends Migration
{
    public function up()
    {
        Schema::create('tickets', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('owner_id')->unsigned();
            $table->integer('operator_id')->unsigned()->nullable();
            $table->timestamps();

            $table->foreign('owner_id')->references('id')->on('users');
            $table->foreign('operator_id')->references('id')->on('users');
        });
    }
    /*...*/
}

class CreateUsersTable extends Migration
{
    public function up()
    {
        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->integer('position_id')->unsigned();
            $table->rememberToken();
            $table->timestamps();

            $table->foreign('position_id')->references('id')->on('positions');
        });
    }
    /*...*/
}
class Ticket extends Model {
    /*...*/
    public function owner() {
        return $this->belongsTo(User::class, 'owner_id');
    }

    public function operator() {
        return $this->belongsTo(User::class, 'operator_id');
    }
}
class User extends Authenticatable {
    /*...*/
    public function ownerTickets() {
        return $this->hasMany(Ticket::class, 'owner_id', 'id');
    }

    public function operatorTickets() {
        return $this->hasMany(Ticket::class, 'operator_id', 'id');
    }
}

Is there good solution for Eloquent model and this relationship? Should I change it?

What you showed is a good solution and there is no need to change it.

The relationships are working fine, for example with this code:

$user = User::find(1);
echo 'Owner ticket count: ' . $user->ownerTickets->count() . '<br>';
echo 'Operator ticket count: ' . $user->operatorTickets->count() . '<br>';

$ticket = Ticket::find(1);
echo 'Ticket owner ID: ' . $ticket->owner->id . '<br>';
echo 'Ticket operator ID: ' . $ticket->operator->id . '<br>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM