Chin Leung
Chin Leung

Reputation: 14921

Laravel 5.6 Reverse HasManyThrough

I have the following table structure in my database:

products

product_formats

product_prices

When I'm trying to do $this->format->product; inside my ProductPrice class, I get an error:

LogicException: App\ProductPrice::product must return a relationship instance.

When I perform a dd inside my function:

dd($this->format()->first()->product);

I get the instance of the product. However, removing the dd would still throw the exception.

Why am I getting the LogicException?


ProductPrice

class ProductPrice extends Model
{
    public function format()
    {
        return $this->belongsTo(ProductFormat::class, 'product_format_id');
    }

    public function product()
    {
        return $this->format->product;
    }
}

ProductFormat

class ProductFormat extends Model
{
    public function product()
    {
        return $this->belongsTo(Product::class);
    }
}

Update

The result of dd($this->format); returns an instance of ProductFormat.

Upvotes: 0

Views: 234

Answers (1)

Chin Leung
Chin Leung

Reputation: 14921

After investigating the HasAttributes::getRelationshipFromMethod(), I've noticed that if the property does not exist in the properties attribute of the class, it will try to retrieve a relation, hence the error.

To fix it, I had to add the following to my class:

protected $attributes = ['product'];

Otherwise, I could call product as a function instead of attribute:

$price->product();

Upvotes: 1

Related Questions