简体   繁体   中英

Laravel access model's property in relation method

I have a relation method for a model which has a condition based on a property of the model itself.

// ProductController.php

    public function show($id, Request $request) {
      $product = Product::find($id);

      if ($request->exists('optionValues') {
         $product->load('optionValues');
      }
    }




// Product.php

    public function optionValues()
    {

/// here $this->stock_status_id is null. actually all attributes array is empty.

        if ($this->stock_status_id == Stock::CUSTOM_ORDER) {
            return $this->hasMany(ProductOptionValue::class, 'product_id', 'product_id')
                ->where('status', 1);
        }

        return $this->hasMany(ProductOptionValue::class, 'product_id', 'product_id')
            ->where('price', '>', 0)
            ->where('quantity', '>', '0')
            ->where('status', 1);

    }

but it seems when Laravel is loading a relation all properties are null. and $this->stock_status_id for current model is null, and I can't check for the condition.

Is there any workaround this problem?

After 2 hours of debugging I discovered that Laravel has different way of loading relations when using $model->load('relationName') method than calling it via $model->relationName

When using ->load('relationName') method the instance of model has no attributes yet even when all attributes have been loaded properly before calling $model->load() .

But when using $model->relationName on a model instance, the instance have all the attributes present when trying to load the relation.

So, I changed this line of code

$product->load('optionValues');

to this:

$product->optionValues;

And the condition checking in the optionValues() method, works as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM