The following tutorial column of Laravel Getting Started will introduce you to the cool operations in Laravel ORM that you don’t know. I hope it will be helpful to friends who need it!
append
class User extends Model { protected $appends = ['is_adult']; public function getIsAdultAttribute() { return $this->attribute['age'] > 18; } }
Have you ever used this operation to add a field to the model that does not exist in the database? Very convenient. But $appends is global, and the is_adult field will be added to all queries.
User::select('id', 'name')->first();
When querying like this, an error message will even be reported indicating that the age field does not exist.
We can add is_adult to the query result set when querying like this.
$user = User::first(); $user->append('is_adult');
Do you think this is over? Not only that, but what if we are querying multiple users? Do we need to for loop and append ourselves? No, no, our elegant Laravel has thought of it for us.
$user = User::paginate(10); $user->each->append('is_adult');
query
User::where('sex', 'girl')->where('age', '<=', 20)->where('money', '>', 1000000000000)->get();
Do you often write this kind of query statement? Did you spot a problem? It's quite rare to find a rich lolita, so I haven't been prompted yet.
How can I bear this? Just rewrite it a little, add query at the front, and marry a rich lolita easily and reach the top of your life.
where
#If you can’t find Rich Lolita, lower your requirements and find a girlfriend seriously. Although it is a bit difficult, if you know her ID, you can directly use
User::query()->find(2);
to find her, it is simple and fast. So what if you don’t know the ID and only know the name? Write where condition? Let me tell you a faster way. After all, you can’t wait to find a girlfriend.
User::query()->firstWhere(['name' => '乔碧萝']);
Write this much first, and update later when you find other cool operations.
For more laravel framework technical articles, please visit laraveltutorial!
The above is the detailed content of Do you know the cool operations in Laravel ORM?. For more information, please follow other related articles on the PHP Chinese website!