joshblevins's avatar

Getting related item from json array.

Is it possible to get a relation to another table using a json array.

I have stored in a column groups that a message is sent to.

["25","4","13","8","3","16","5","9","7"]
	

If I set the relationship up is their a way to echo out the group name rather than the number

0 likes
2 replies
frankincredible's avatar
Level 14

So you have a table, say messages, which has a json column type, group_ids that stores an array of group_ids... and you want to join to a groups table to get the $group->name?

Is my summary above accurate?

I'm not sure you'd be able to do that exactly as you have it defined.

Some possible avenues to explore however:

  1. Move that field into a group_message pivot table that would contain a message_id and a group_id, and define a Many To Many relationship using a belongsToMany(Groups::class) and a hasMany(Messages::class) on your models.

  2. Use Caleb Porzio's Sushi package which allows you to treat an array like an Eloquent Model. It looks like you'd use the package's public function getRows() method, and pass the rows into the Sushi model's constructor? The problem with this approach is I don't think it would work well for a collection of Messages because you'd probably have to send the group_ids for every Message in the collection to a separate GroupMessage sushi model's constructor. Anyways, here's a link to the repo if you want to do some research on that package: https://github.com/calebporzio/sushi

Ultimately, your best bet is create a pivot table, group_message, and to write a job to migrate all of your messages records' group_ids to new records in that pivot table.

tlacaelelrl's avatar

Assuming you have a JSON property in your database with the name myrelationids you could do the following:

<?php

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;

class MyModelWithRelations extends Model {
    protected $casts = [
        'myrelationids' => 'array'
    ];

    protected function myrelationids(): Attribute {
        return Attribute::make(
            get: function($value){
                $ids = json_decode($value);
                if(!is_array($ids)){
                    return [];
                }
                return TheModelOfTheRelation::whereIn('id', $ids)->get();
            },
        );
    }
}

On another note, if ids are numeric, save them as integer values, instead of

["25","4","13","8","3","16","5","9","7"]

Save as

[25,4,13,8,3,16,5,9,7]
1 like

Please or to participate in this conversation.