繁体   English   中英

如何在Laravel Eloquent中正确创建两个引用同一表的外键的关系?

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

我已经在代码中如下创建了Relationshiop。 在“票证”表中,我使用了两个引用“用户”表的外键。 当我使用票证模型中的operator nad creator方法时,它可以正常工作。 但是,当我想从用户模型获取ownerTickets或operatorTickets时,我会得到null。 我不确定是否正确调用了这些方法。

我的数据库已满,我看到该用户是所有者或操作员。

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

Eloquent模型和这种关系是否有好的解决方案? 我应该改变它吗?

您显示的是一个很好的解决方案,无需更改它。

关系可以正常工作,例如使用以下代码:

$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>';

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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