#explode model relation

4 messages · Page 1 of 1 (latest)

fading musk
#

Hi, I ran in to a little issue, I am trying to get the relation nodes of my product, however, it has to be an relation, and can not be a collection:

     * Gets the nodes associated with a product.
     */
    public function nodes(): HasMany
    {
        $node_ids = explode(',', $this->node_ids);

        return $this->hasMany(Node::class, 'id', 'node_ids')->whereIn('id', $node_ids);
    }```

I know with `Node::whereIn('id', $node_ids)->all()` it would've been done, but like I said, I need it to be a relation. Which is why I tried this above ^^, which I thought would work, but sadly, it only returns me the first node, not the second, third or any more.

`node_ids` is currently a imploded string with node id's  `1,2,3,4`

Anyone an idea how I can do this?
south crane
#

That's not going to work, because what you've stored is not a relation
Not sure what the relation is that you're going for, but if it's one-to-many you'd store the product ID on the Node model, so the nodes table would have a product_id. Or if you want a many-to-many, you'd need to set it up as a many-to-many relation; https://laravel.com/docs/10.x/eloquent-relationships#many-to-many

fading musk
#

nodes doesn't have any product variable saved on them, but products have a node_ids variable which includes all node id's the product belongs too in a imploded string format