【问题标题】:Laravel - how to return an array from a Model method?Laravel - 如何从模型方法返回数组?
【发布时间】:2019-09-17 13:53:02
【问题描述】:

我有一个模型方法,我试图返回一个开始和结束日期。

像这样:

public function start_end_date()
    {

        $instances = $this->hasMany(Instance::class, 'instance_id')
            ->where('instance_id', '=', $this->id)
            ->where('weekstart', '>=', time());

        $dates = $instances->pluck('weekstart')->toArray();
        $dates = array_map('strtotime', $dates);
        $startdate = min($dates);
        $enddate = strtotime("+7 day", max($dates));

        return array('startdate' => $startdate, 'enddate' => $enddate);
    }

在我看来,我已将$courses 传递给视图。该对象通过其模型返回courseinstances,如

 public function courseinstances()
    {

        return $this->hasMany(CcoursesInstance::class, 'course_id')
            ->where('startdate', '>=', time());
    }

因此,鉴于我可以循环遍历 $courses(例如 @foreach $courses as $course)并循环遍历实例(例如 @foreach $course->courseinstances as @instance)并且效果很好。例如,我可以访问某些字段或方法返回的值作为$instance->somedata

但在我有$course->courseinstances->start_end_date->startdate的视图中

Laravel 说

Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation (View:

我只是想不通 Laravel 希望我如何返回开始和结束日期,然后在视图中引用它。我不想将单独的变量传递给视图。我只想使用传递给视图的 $courses,然后像处理与课程相关的其他数据一样向下钻取。

想法?

谢谢, 布赖恩

【问题讨论】:

    标签: laravel


    【解决方案1】:

    start_end_date 不是属性,它是一种方法,因此您需要将其声明为属性,而且$instances 正在返回一个查询构建器实例,而不是您可以从中提取的集合,因此将get() 附加到实际检索记录

    public function getStartEndDateAttribute()
    {
        $instances = $this->hasMany(Instance::class, 'instance_id')
                          ->where('instance_id', '=', $this->id)
                          ->where('weekstart', '>=', time())->get();
    }
    

    【讨论】:

    • 不使用 get() 代码仍然有效(可能是因为我在 Laravel 5.3 上)。但只是不确定所需的 return 语句的语法以及我需要在视图中使用什么引用语法。只需在此处阅读laravel.com/docs/5.3/eloquent-mutators 关于 Mutators 的信息,但似乎假设您正在引用列名。就我而言,没有列名,因为我正在动态生成开始日期和结束日期。
    • 这是一个访问器,与列名无关,修改器以set而不是get开头
    • 在 Laravel 5.3 文档中,它说“要定义访问器,请在您的模型上创建一个 getFooAttribute 方法,其中 Foo 是您希望访问的列的“研究”大小写名称”如果我使用函数命名getStart_end_dateAttribute(),并在视图中使用$instance->start_end_date['startdate'],该方法没有被调用。
    • 好的,搞清楚了。需要重命名函数 getStartEndDateAttribute() - 感谢您帮助我解决这个问题!
    • 我使用这种方法的次数越多,我就越意识到它是有缺陷的,因为在我的后端我有角度控制器。似乎这些自定义属性以角度工作我需要使用受保护的附加,这会导致奇怪的行为(比如在不应该调用 get 属性方法时。所以现在我又回到了原点,想知道如何制作 start_end_date( ) 模型方法返回所需的数据形式,以便在刀片或角度控制器中我可以访问为$instance->start_end_date 或角度instance.start_end_date
    【解决方案2】:

    这是一个数组,所以你应该通过它的数组索引来获取值,如下所示:

    $course->courseinstances->start_end_date['startdate']
    

    【讨论】:

      猜你喜欢
      • 2021-11-25
      • 2014-11-20
      • 1970-01-01
      • 2013-12-26
      • 2020-11-06
      • 2016-03-28
      • 1970-01-01
      • 2011-04-14
      相关资源
      最近更新 更多