1

I'm wanting to create a laravel model with a computed column. I've seen how to do this once the data is downloaded however the computation I wish to do is expensive but accessible as a function in my sql. Essentially I'd like to append one more column to the query builder but I'm unsure how to go about it.

The query needs to be something like:

select *, my_function(ID) as my_value from my_table;

and I need to get an instance of the model in return (not a raw recordset).

I'm also hoping to avoid multiple queries.

Thanks.

1

2 Answers 2

5

Your query can be something like this:

User::select([
   'users.*',
   \DB::raw('YEAR(created_at) as year')
])->get()

Replace YEAR function with whatever function you want. should append to the results that column as well.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. That's exactly what I'm after
0

Building on the answer from musicvicious I ended up going with:

class User extends Model
{
...

    public function newQuery()
    {
        return parent::newQuery()->select('users.*', \DB::raw('YEAR(created_at) as year'));
    }

}

Now I can just fetch the models as normal.

User::all();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.