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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With