I
I
Ilya2019-04-05 20:19:32
Laravel
Ilya, 2019-04-05 20:19:32

How to change the names of the model fields when select?

There is an Eloquent model and a table associated with it. It has a field, let's say "PROPERTY_155".
How can I make it so that I specify the "VENDOR" field in the select method, but the request leaves with the choice of the "PROPERTY_155" field.
By overriding the getAttribute method, I managed to make a call to the desired key, but I just can’t do the same thing with select.

$rows = ProductProperty::select(['PROPERTY_155', 'PROPERTY_77'])
  ->where('IBLOCK_ELEMENT_ID', '=', 26072)
  ->get();

$row = $rows->first();

var_dump($row->VENDOR);         //string(5) "18980" это значение содержится в поле PROPERTY_155
var_dump($row->VENDOR_COUNTRY); //string(3) "475"  это значение содержится в поле PROPERTY_77


//так переопределяю названия полей в модели ProductProperty, при обращении к ним
public function getAttribute($key)
{
  if (!self::$propertyNames) {
    $this->setPropertyNames();
  }

  if (isset(self::$propertyNames[$key])) {
    $key = 'PROPERTY_' . self::$propertyNames[$key]['ID'];
  }

  return parent::getAttribute($key);
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
JhaoDa, 2019-04-05
@JhaoDa

ProductProperty::select(['PROPERTY_155 as VENDOR', 'PROPERTY_77'])...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question