Laravel:如何在我的模型上用自己的查询编写onw函数?

时间:2017-02-27 22:22:16

标签: php laravel-5 eloquent

实施例: 我想为laravel模型创建我自己的函数,如:

(原始查询)

SELECT
   AVG(persons_positions.points)
FROM
    positions
INNER JOIN persons_positions ON (
    positions.id = persons_positions.position_id
)
WHERE positions.country = 1
AND persons_positions.person_id = 2

(模特班)

class Menedzher extends Model {
    function oh ($x) {
        return DB::table('positions')
            ->join('persons_positions', 'positions.id', '=', 'persons_positions.position_id')
            ->where('positions.country', $x) // see here
            ->where('persons_positions.person_id', '=', $this->id ) // see it!!
            ->select(DB::raw('AVG(persons_positions.hits)'));

    }
}

并使用它:

Menedzher :: GET(1) - > OH(3)

谢谢!

1 个答案:

答案 0 :(得分:1)

在您的位置模型中建立一个关系,如下所示

public function oh() {
        return $this->hasOne('persons_positions')
            ->selectRaw('avg(hits) as hits, person_id')
            ->groupBy('person_id');
    }

然后在控制器中执行此操作

$user = Position::with('oh')->get();