Tuesday, May 23, 2017

Eloquent hasMany relationship - can I retrieve an item by a seperate key's value?

I have set up a hasMany relationship between a model called Supplier, and a model called SupplierMeta.

SupplierMeta is linked to a table with the structure:

id, supplier_id, name, value

and the Supplier model has the following relationship defined:

public function meta() {
    return $this->hasMany('Model\SupplierMeta');
}

The relationship itself works fine, but what I would like to do is define another function that searches within that relationship by the "name" field and returns the value. I would like it to work in this format:

$supplier->meta->field_name, or $supplier->meta()->field_name

This would either return the "value" field of the relevant SupplierMeta object, if it exists, or otherwise return false. Is this possible?



via Tom Haddad

Advertisement