简体   繁体   English

Laravel模型函数使用关系

[英]Laravel Model function using relationship

I made this function in my view for summing total hours 我认为此功能用于汇总总时数

<?php 

     $sum = [];
     foreach($user->workedTimes as $item){
        array_push($sum, ($item->end_time->diffInHours($item->start_time))); 
     }
     echo array_sum($sum);

?>

And in blade view all is fine, but i want that same code in my Model so i can call user->totalHours in blade 在刀片视图中一切都很好,但是我想要在我的模型中使用相同的代码,以便可以在刀片中调用user-> totalHours

and i made this function in my Model: 我在模型中做了这个功能:

在此处输入图片说明

and when i call {{ $user->totalHours }} 当我致电{{$ user-> totalHours}}

i get this error: 我收到此错误:

在此处输入图片说明

How to make this work from Model?? 如何通过Model进行这项工作?

You should use the method with brackets like this: 您应该使用带有方括号的方法,如下所示:

{{ $user->totalHours() }}

But it would be good if you use Laravel Accessor like this: 但是,如果您像这样使用Laravel Accessor ,那就太好了:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function getTotalTimeAttribute()
    {
       // Your logic here ...
       $sum = [];
       foreach($this->workedTimes as $item) {
         array_push($sum, $item->end_time->diffInHours($item->start_time));
       }
       return array_sum($sum);
    }
}

and access it in blade like this: 并以如下方式在刀片中访问它:

{{ $user->total_time }}

Hope this helps! 希望这可以帮助!

尝试使用$this->workedHours()并使用$user->totalHours()调用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM