#php #laravel #eloquent
#php #laravel #красноречивый
Вопрос:
Привет, ребята, я безуспешно пытаюсь добавить предложение where в свой пользовательский атрибут «ateco».
Моя модель
class AtcReportRule extends Model
{
protected $fillable = [
'intermediary_id',
'atc_report_rule_id',
'atc_report_kpi_id',
'operator',
'value',
'important',
'flag',
'type'
];
public function setAtecoAttribute()
{
$ruleValue = str_replace(".","", $this->value);
preg_match_all('!d !', $ruleValue, $matches);
if ( isset($matches[0][0]) ) {
// a volte capita N.N Oppure A.A ecc
$ruleValue = $matches[0][0];
}
$this->attributes['ateco'] = $ruleValue;
}
public function childrens() {
return $this->hasMany('ModulesAtcEntitiesAtcReportRule','atc_report_rule_id')->orderBy("order");
}
}
ЗАПРОС
$ruleChildren = $atcReportRule->childrens->where("ateco","some_value")->first()
возвращает значение null без значения. Следующий код не имеет атрибута «ateco»
ТЕСТ
dd($atcReportRule->childrens[0])
Комментарии:
1. Я не совсем понимаю, в чем проблема. Где вы пытаетесь установить значение
AtcReportRule::$ateco
для запуска мутатора? Где выполняется этот запрос?2. я попытался использовать mutator для добавления нового атрибута в мою модель. Этот новый параметр я буду использовать в своем запросе => $ruleChildren = $atcReportRule-> childrens->where(«ateco»,»some_value»)->first()
3. я опубликовал решение
Ответ №1:
Ваш тест не возвращает ateco
атрибут, поэтому ваш запрос также возвращает null.
если вы:
$ruleChildren = $atcReportRule->childrens->where("atc_report_rule_id","some_value")->first()
Тогда это будет работать. Вот ваше решение: https://laravel.com/docs/master/eloquent-serialization#appending-values-to-json
После определения метода доступа вам также необходимо добавить его в ответ json.
protected $appends = ['ateco'];
Комментарии:
1. измените этот «setAtecoAttribute» на «getAtecoAttribute»
2. измените это «$this->attributes[‘ateco’] = $ruleValue;» на «return $ruleValue;»
Ответ №2:
я исправил так:
/**
* Get the user's full name.
*
* @return string
*/
protected $appends = ['ateco'];
public function getAtecoAttribute()
{
$ruleValue = str_replace(".","", $this->value);
preg_match_all('!d !', $ruleValue, $matches);
if ( isset($matches[0][0]) ) {
// a volte capita N.N Oppure A.A ecc
$ruleValue = $matches[0][0];
}
return $ruleValue;
}
тогда я могу сделать это:
$atcReportRule->childrens->where("ateco","some_value")->first();