Laravel:从Ticket Model到两个User Model实例的两个外键

时间:2016-04-19 06:26:36

标签: laravel eloquent foreign-keys relational-database

我正在做一个小票预订服务。我的目标是将票证模型链接到两个用户实例:1。创建票证的经理2.拥有票证的用户。

我有两种模式:

用户

id
name
email
manager

模型

public function myticket() {
return $this->hasMany(App::Ticket);
} //this is for the ticket owner

public function createdticket() {
return $this->hasMany(App::Ticket);
} //this is for the manager who created the ticket

票务

id
ticketcode

$table->integer(user_id)->unsigned(); //the user who owns the ticket
$table->foreign('user_id')->references('id')->on('users');

$table->integer(manager_id)->unsigned(); //the manager who created 
$table->foreign('manager_id')->references('id')->on('users');

模型

public function user() {
return $this->belongsTo(App::User);
} //this is for the ticket owner

public function createdby() {
return $this->belongsTo(App::User);
} //this is for the manager who created the ticket

如何调整我的代码以使这种说法符合要求?

1 个答案:

答案 0 :(得分:1)

唯一的事情是在你的关系中添加精确的列。

User模型中应该是:

public function myticket() 
{
    return $this->hasMany(App::Ticket, 'user_id');
} //this is for the ticket owner

public function createdticket() 
{
    return $this->hasMany(App::Ticket, 'manager_id');
} //this is for the manager who created the ticket

对于Ticket模型,它应该是:

public function user() 
{
   return $this->belongsTo(App::User, 'user_id');
} //this is for the ticket owner

public function createdBy() 
{
   return $this->belongsTo(App::User,'manager_id');
} //this is for the manager who created the ticket

您可以忽略这些关系中的user_id,因为默认情况下,如果您与其他名称和多个用户有关系以便于阅读,那么最好将其包括在内