首页 > 解决方案 > 在运行时在集合上添加属性追加

问题描述

 class Student extends Model
 {
    .... some code here

    public function getGroupAttribute()
    {
        if($this->group == 1)
           return  'Group A';
        else
           return 'No Group';
    }
 }

我知道有 setAppends() 功能,但该功能仅适用于单个模型。而且我也知道在类中将 $appends 变量定义为的静态方式:

protected $appends = ['group']; // but this is not changable if I did it like this.

如何在控制器的运行时实现 set $append ?

  //inside controller

  public function getStudent()
  {
      Student::whereIn('id',[1,4,10,21])->get(); // I want to set the $appends value here
  }

标签: laravellaravel-5attributesappend

解决方案


你试过用pluck吗?

Student::whereIn('id',[1,4,10,21])->pluck('group');

基于 检索列值列表


推荐阅读