1

Similar to linking issues in Jira or work items in ADO. What's the best way (in Laravel) to go about saying tickets 1, 2, 3, 4, and 9 are all "related" to each other and no matter which record I'm looking at I see the full list of related records. Looking for help on both a table structure and model.

  • It depends: if your models are the same, e.g. `Ticket` model only relates to `Ticket` models. Could you sketch your current scenario? – dbf Aug 23 '23 at 18:02

1 Answers1

1

I think I roughly (if not efficiently) got where I was trying to go using this as a guide: https://github.com/laravel/framework/issues/441

Migration

public function up()
{
    Schema::create('related_tickets', function (Blueprint $table) {
        $table->id();            
        $table->integer('related_id')->unsigned()->index();
        $table->integer('ticket_id')->unsigned()->index();
        $table->foreign('related_id')->references('id')->on('tickets')->onDelete('cascade');
        $table->foreign('ticket_id')->references('id')->on('tickets')->onDelete('cascade');
    });
}

Model

public function related_tickets()
{
    return $this->belongsToMany('App\Models\Ticket', 'related_tickets', 'ticket_id', 'related_id');
}
public function add_related_ticket($related_id)
{
    $related = $this->related_tickets()->pluck('tickets.id')->all();
    array_push($related, $related_id);
    array_push($related, $this->id);
    foreach($related as $ticket_id){
        $ticket = Ticket::find($ticket_id);
        $related_no_self = array_diff($related, array($ticket->id));
        $ticket->related_tickets()->sync($related_no_self);
    }
}
  • 1
    why load the ticket model if all you need is the id that you already have? – kris gjika Aug 24 '23 at 12:19
  • @krisgjika - For the original ticket it is definitely redundant to reload the ticket model. It would also be safer to use recursion to make sure that we start with the superset of related tickets instead of assuming everything is already linked correctly and the original ticket is correctly linked to all related tickets. This was more a proof of concept. – Charlie Grove Aug 24 '23 at 15:56