[英]How to properly create a relationship two foreign keys referencing same table in Laravel Eloquent?
I've created relationshiop as below in the code. 我已经在代码中如下创建了Relationshiop。 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.
当我使用票证模型中的operator nad creator方法时,它可以正常工作。 But when I want to get ownerTickets or operatorTickets from User model i get null.
但是,当我想从用户模型获取ownerTickets或operatorTickets时,我会得到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? Eloquent模型和这种关系是否有好的解决方案? 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>';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.