eloquent - Laravel: Two foreign keys to from Ticket Model to two instances of User Model -
i'm making small ticket booking service. goal link ticket model 2 user instances: 1. manager created ticket 2. user owns ticket.
i have 2 models:
user
table
id name email manager
model
public function myticket() { return $this->hasmany(app::ticket); } //this ticket owner public function createdticket() { return $this->hasmany(app::ticket); } //this manager created ticket
ticket
table
id ticketcode $table->integer(user_id)->unsigned(); //the user owns ticket $table->foreign('user_id')->references('id')->on('users'); $table->integer(manager_id)->unsigned(); //the manager created $table->foreign('manager_id')->references('id')->on('users');
model
public function user() { return $this->belongsto(app::user); } //this ticket owner public function createdby() { return $this->belongsto(app::user); } //this manager created ticket
how can adjust code make eloquent compliant?
the thing adding exact columns relations.
in user
model should be:
public function myticket() { return $this->hasmany(app::ticket, 'user_id'); } //this ticket owner public function createdticket() { return $this->hasmany(app::ticket, 'manager_id'); } //this manager created ticket
and ticket
model should be:
public function user() { return $this->belongsto(app::user, 'user_id'); } //this ticket owner public function createdby() { return $this->belongsto(app::user,'manager_id'); } //this manager created ticket
you can ignore user_id
in relationships because it's default, in case have relations other names , multiple users readability it's better include them
Comments
Post a Comment