How to injecting custom columns in Laravel query builder

风流意气都作罢 提交于 2019-12-06 11:02:52

I can think of three methods. For example, let's say you want to get the difference between the columns c and e.

Select with raw expressions

With raw expressions you can use all available SQL functions and ordinary math operators as well. Basically you can do everything what you could in a normal SQL select because Laravel will insert the string directly into the query.

$result = DB::table('a')
    ->join('b')
    ->where('c')
    ->orderBy('d')
    ->select('e', DB::raw('c - e AS differenceCE'));

Now the result will have a differenceCE property containing the result of the division.

Attribute accessors

This only works with Eloquent Models!

You can create a new dynamic attribute in your model, that will be calculated the moment you access it

class MyModel extends Eloquent {
    protected $appends = array('difference');

    public function getDifferenceAttribute(){
        return $this->attributes['c'] - $this->attributes['e'];
    }
}

Access the property:

$mymodel->difference;

for(each)

You can also use a simple loop like:

foreach($result as $model){
    // do math
}

Or if you're using Eloquent there's the each method you can call on a collection

$result->each(function($model){
    // do math
});

Just be aware that method 1 and 2 may result in (slightly) better performance. SQL just because it has to go through every record anyways and the method with the attribute accessor has the advantage that it will be lazy loaded. Meaning the calculation only happens when you use it (when you access the property)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!