【问题标题】:Laravel Paginate with Dynamic MethodLaravel 使用动态方法进行分页
【发布时间】:2017-08-03 06:47:25
【问题描述】:

我正在 Laravel 上构建一个 REST API。我目前有一个模型( Project ),它有 2 个动态方法( liveindexes 和 totalindexes )。

我希望 API (/projects) 也能返回这两种方法的值。

项目负责人

public function index()
{
     return Project::paginate();
}

项目模型

class Project extends Model
{
      protected $table = 'projects';

      protected $fillable = [
          'target'
      ];

      public function indexes()
      {
          return $this->hasMany('App\indexes','project_id','id');
      }

      public function totalindexes()
      {
          return $this->indexes()->count();
      }

      public function liveindexes()
      {
          return $this->indexes()->whereNotNull('anchor')->count();
      }
}

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    要将这些项目包含在您的 Project 模型中,请将它们添加到模型的属性中,当模型转换为数组或 JSON 形式时,属性会被附加。

    将此添加到您的代码中:

    protected $appends = ['live_indexes', 'total_indexes'];
    
    public function getLiveIndexesAttribute() {
        return $this->attributes['live_indexes'] = $this->liveIndexes();
    } 
    
    public function getTotalIndexes() {
        return $this->attributes['total_indexes'] = $this->totalindexes();
    }
    

    【讨论】:

    • 之前试过这个。我收到以下错误 Call to a member function addEagerConstraints() on integer
    • 啊,对不起。我没有意识到你在计算结果。检查我的更新答案
    • 成功了!我还可以使用闭包函数和 withCount 方法来实现这一点。我还是更喜欢你的方法。
    猜你喜欢
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-01
    • 2020-04-21
    • 1970-01-01
    相关资源
    最近更新 更多