Home > Blockchain >  is it possible to set a foreign key column that can be related to more than a table
is it possible to set a foreign key column that can be related to more than a table

Time:12-22

I have a ticket booking system for a traveling company. I have a ticket table, bus table, plane table, and steamship table. The tickets table has a transport_id column that can have a relation with any of these tables. Is this possible in SQL or is there a good trick to do it with laravel?

I thought about making another column called, say, type that has a table name and get the rows I need with an eloquent like this:

public function transports()
{
   $transport = DB::table($this->type)->where('id', $this->transport_id)->get();
   return DB::table('tickets')->where('id', $transport->id)->first();
}

// in transport Models
public function tickets()
{
   return Ticket::where("type", "TABLE_NAME")->all();
}

This way seems a little hacky. I just want to know if there's a function or something to do this in a better way.

CodePudding user response:

You can use Laravel's Eloquent one-to-many polymorphic relation:

If you follow the table structure you can query like:

class Ticket extends Model
{
    /**
     * Get the parent transport model (buss, plane, etc).
     */
    public function ticketable()
    {
        return $this->morphTo();
    }
}
 
class Plane extends Model
{
    /**
     * Get all of the plane's tickets.
     */
    public function tickets()
    {
        return $this->morphMany(Ticket::class, 'ticketable');
    }
}
  • Related