如何从Laravel Eloquent中的HasMany关系中的联接表中获取特定列

时间:2016-05-11 06:39:48

标签: php mysql laravel-5.1

我的模型看起来像这样

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class appraisaltask extends Model
{
    //
     protected $table = 'empappraisaltask';

    /*
     * An invoice can has many payments 
     *
     */
     public function ratings(){

        return $this->hasMany('App\appraisalrating','empappraisaltask_id')->select(array('comment', 'rating'));
    }
}

我在我的函数中进行查询

 public function getUserbasictask(){

        $taskwithcomments = appraisaltask::select(array('id','taskname','description','status'))->with(  array('ratings' => function($query)
          {
             // the condition that will be apply on the with relation
              $query->where('emp_id','=',Auth::user()->empid);

          }))->where('type','=','basic')->get();

            return json_encode($taskwithcomments);
    }

但我得到了空Rating个对象。任何建议如何做到

如果我从模型中的评级功能中删除select(),我将获得所有详细信息

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

i got your issue,update your ratings function in appraisaltask model

public function ratings()
{
    return $this->hasMany('App\appraisalrating','empappraisaltask_id')->select(array('emp_id','comment', 'rating'));
}

and also update query

 public function getUserbasictask(){
    $taskwithcomments = appraisaltask::select(array('id','taskname','description','status'))
->with(['ratings' => function($query)
      {
         // the condition that will be apply on the with relation
          $query->where('emp_id','=',Auth::user()->empid);

      }])->where('type','=','basic')->get();

        return json_encode($taskwithcomments);
}

hope it will work.