Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent model add extra column by default

I have a model called Book and I want to add an extra column to the default SQL.

At the moment the default sql looks like this:

SELECT * FROM `books`

But I want the default SQL to look like this:

SELECT *, "Hello" as `greeting` FROM `books`

So that I can do the following:

// in a controller function...
$book = Book::find(1);
echo $book->greeting; // Hello

$books = Book::all();
foreach($books as $book){
    echo $book->greeting; // Hello
}

Is there any way I can achieve this?

Many thanks

like image 914
Thomas Clayson Avatar asked Dec 24 '22 23:12

Thomas Clayson


1 Answers

Even though I wonder what the reason behind this is, you could override newQuery in your model

public function newQuery(){
    $query = parent::newQuery();
    return $query->selectRaw('*, "Hello" AS greeting');
}

Another way would be to use a scope:

public function scopeWithGreeting($query){
    return $query->selectRaw('*, "Hello" AS greeting');
}

Usage:

$book = Book::withGreeting()->find(1);

If you really want the scope every time, you can use a global scope so you don't have to call withGreeting all the time.

like image 77
lukasgeiter Avatar answered Dec 27 '22 18:12

lukasgeiter