在eloquent模型中添加自定义属性

rap*_*2-h 2 php postgresql laravel eloquent laravel-5

这是一个原始SQL查询:

SELECT name, area, point(area) AS center FROM places;
Run Code Online (Sandbox Code Playgroud)

我想基于此查询获得一个Eloquent模型.这是模型:

class Place extends Model
{
    protected $visible = ['name', 'area'];
}
Run Code Online (Sandbox Code Playgroud)

所以,center如果我运行此代码,我想获取属性:

return response()->json( Place::all() );
Run Code Online (Sandbox Code Playgroud)

center不见了.我不知道如何center在我的Place对象中添加属性.我不想在我的控制器中构建一个原始查询,是否有任何解决方案与mutator或类似的东西?(我唯一想说的是Place::all(),我真的想在控制器中使用Eloquent Model,而不是SQL查询).

Ame*_*lia 6

使用Mutators和$appends属性的组合.这是一个例子:

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Place extends Model {

    protected $appends = ['center'];

    public function getCenterAttribute()
    {
        return $this->point($this->getRawAttribute("area"));
    }

    protected function point($area)
    {
        // logic for SQL POINT(), etc
    }
}
Run Code Online (Sandbox Code Playgroud)

$appends属性意味着当调用$model->toJson()$model->toArray()调用时,mutated属性包含在JSON /数组输出中(Response::json()确实如此)

在代码中执行点逻辑的原因是因为使用雄辩的模型,在获取场所及其中心列表时,您会遇到N + 1查询问题,这对您的数据库来说不是一个好主意.

从数据库中获取模型的数据时,也不会使用您的查询,因为模型的默认查询是

select * from `table` where id = :id
Run Code Online (Sandbox Code Playgroud)

然后在内部计算出在模型上设置数据.