Home  >  Article  >  PHP Framework  >  Do you know the cool operations in Laravel ORM?

Do you know the cool operations in Laravel ORM?

藏色散人
藏色散人forward
2020-05-18 16:26:072984browse

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!

Do you know the cool operations in Laravel ORM?

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(&#39;sex&#39;, &#39;girl&#39;)->where(&#39;age&#39;, &#39;<=&#39;, 20)->where(&#39;money&#39;, &#39;>&#39;, 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.

Do you know the cool operations in Laravel ORM?

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.

Do you know the cool operations in Laravel ORM?

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([&#39;name&#39; => &#39;乔碧萝&#39;]);

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!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete