代码之家  ›  专栏  ›  技术社区  ›  Kapitan Teemo

仅获取一列,并使用laravel中的“with()”函数为该列创建别名

  •  0
  • Kapitan Teemo  · 技术社区  · 7 年前

    我有两张桌子, JobOrder Job . 我使用一对多关系。

    工作 工单 工单 工作 .

    public function job()
    {
        return $this->belongsTo(Job::class);
    }
    

    public function getAllJobOrder()
    {
        $results = JobOrder::with('job')->get();
        return $results;
    }
    

    上面的代码返回如下数据:

    enter image description here

    我只想得到 job->position enter image description here

    实际上,我可以使用 withCount 但我认为这不是正确的方法。

    public function getAllJobOrder()
    {
        $results = JobOrder::withCount(['job AS position' => function ($q) {
                $q->select('position');
            }])->get();
        return $results;
    }
    

    带计数 ?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Jinal Somaiya    7 年前

    控制器

    public function getAllJobOrder()
    {
        $results = JobOrder::with('job')->get();
        foreach($results as $result){
           $result->position = $result->job->position;
           unset($result->job);
        } 
        return $results;
    }