簡體   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