Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

Hum,

Maybe something like this ..

public function children()
    {
        return $this->hasMany('App\Child', 'my_model_id', 'id')->where('child.data', 1);
    }

You lose the attribute value but since it is the same as the child->data you still have the value, just with a different key.

I'm not 100% on the where statement, but I think i did something similar somewhere, but... not enough caffeine yet today.

0

That's an interesting thought with the dot notation, I forget you can do that.

That's good for filtering but I do want to return all the child models even if child.data != 1, and then calculate the attribute based on the child.data values as a whole. I guess that's where my situation gets a bit tricky.

For example, if any of child.data = 1, i want MyModel->attribute = 1. If all of child.data = 0, MyModel->attribute = 0

I ended up fetching all the results first, then looping through the Child collection, extracting a result, then merging the attribute manually into the collection.

I guess I'm thinking it would be nice if the getModelStatusAttribute could "share" the data returned from the ->children() method. But that seems to be resolved AFTER the model attributes are set...

NOTE: I changed getChildStatusAttribute to getModelStatusAttribute, to reflect more clearly what I'm aiming for

Last updated 8 years ago.
0

Humm..

What about using $this->children in the getModelStatusAttribute function instead of calling Child again?

Also, the attribute value is set to 1 when the first child with a data is equal to 1, not sure about the continued looping over the children since it never changes.

Here are the code notes,


public function children()
    {
        return $this->hasMany('App\Child', 'my_model_id', 'id');
    }

 public function getModelStatusAttribute()
    {
        /* inefficient - the children() method already
           causes the query builder to lookup children */
       // $children = Child::where('my_model_id', $this->id)->get();
        // Perhaps changing this to ...
        $children = $this->children(); // with the change to the children function to include the my_model_id relationship

        $attribute = 0;

        foreach($children as $child) {
            if ($child->data == 1) {
                $attribute = 1;  // <== it is one from this point, for every child past
                break;  // ?? maybe since no need to continue looping the children
            }
        }

        return $attribute;
    }
0

Sign in to participate in this thread!

Eventy

Your banner here too?

heisian heisian Joined 27 Jan 2016

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.