如果模型具有访问器,Laravel object 值与 Blade 语句不起作用

Laravel object value with Blade statement does not work if model has accessor

我有一个 Laravel object 型号,带有访问器:

class NutritionalPlanRow extends Model
{
    use HasFactory;

    private $nomeAlimento;

    public function __construct($aliment = null,
                                array $attributes = array())  {

        parent::__construct($attributes);

        if($aliment){
            $this->aliment()->associate($aliment);
            $this->nomeAlimento = $aliment->nome;
        }
    }

    public function aliment()
    {
        return $this->belongsTo('App\Models\Aliment');
    }

    protected $guarded = [];

    public function getNomeAlimentoAttribute()
    {
        return $this->nomeAlimento;
    }
}

我想在 Blade 页面中使用 Blade 语句打印 nomeAlimento 值,例如:

 .
 .
 <tbody>
     @foreach( $plan->nutritionalPlanRows as $planRow )
     <tr>
         <td>
             {{ $planRow->nomeAlimento}}
         </td>
   .
   .

但 table 单元格内的值未打印,就好像 $planRow->foodName 为空。实际上它不是空的,实际上如果我打印 {{$planRow}} object 的结构是完整的,并且所有属性都已设置。 我注意到,如果在模型中删除访问器 (getNomeAlimentoAttribute()),则 blade 页面中的值会正确打印。

为什么?

谢谢。

有几点需要注意:

第一:为什么需要构造函数?您可以在没有构造函数的情况下定义计算属性

use App\Models\Aliment;

class NutritionalPlanRow extends Model
{
    use HasFactory;
  
   

    public function aliment()
    {
        return $this->belongsTo(Aliment::class);
    }

    protected $guarded = [];

    public function getNomeAlimentoAttribute()
    {
        return optional($this->ailment)->nome;
    }
}

其次:在 Eloquent 模型 class 中使用构造函数设置关系时,似乎有代码味道。理想情况下,关系应该 set/associated 来自 Controller。

第三:我觉得不需要在 class 上将 $nomeAlimento 声明为私有 属性。在 Laravel 中计算 properties/attributes 可以提供访问器。

更新:

class Patient extends Model
{
    use HasFactory;


    protected $dates = ['day_born'];
    protected $guarded = [];

    public function getYearsAttribute(){
        
        Log::info('patient all data '.$this);  //Print correct all data
        Log::info('Day'.$this->day_born); //print empty
        
        
        return Carbon::parse($this->day_born)->diffForHumans(now());
    }
}

阅读 https://carbon.nesbot.com/docs/ 以获得更多好东西。