Author: Shiannizhilu public number: Zhixing Research Institute

6.1 Creating a Model

A model is a binding between a table and a model. Model creation method:

php artisan make:model Http/Models/User
Copy the code

Note here that if Laravel is a new version, there will be a Models folder under the app file by default, and there will be an initial user.php model, which is generated by middleware permission control by default. If you continue with the above command, a series of new files will be created under the Models folder.

So, for the new version of Laravel, you should create the model using the following command:

php artisan make:model Models/User
Copy the code

6.2 Default Settings

1. The Laravel framework uses the Eloquent ORM for database interaction, also known as the Relational Object Model.

When called, the table name should follow Laravel’s default rule, which is that the table name should be complex (after all, the framework developed by foreigners).

If the table name is not complex, there are two solutions, one is to change the database name, the other is to specify the table name:

class User extends Model
{
    // Use the following code to specify the table name
    protected $table = 'user';
}
Copy the code

3. The default primary key is ID. If you want to change the default primary key, you can specify:

protected $primaryKey = 'uid';
Copy the code

The default primary key ID is autoincrement, which means that the primary key is automatically converted to an int. If you want a non-incrementing, non-numeric primary key, you can set it to cancel:

public $incrementing = false;
Copy the code

If the primary key is not an integer, then you need to set $keyType to string:

protected $keyType = 'string';
Copy the code

4. The default creation and modification timestamp fields are created_at and updated_at.

If you do not want the system to take over these columns, you can set false to cancel:

public $timestamps = false;
Copy the code

If you want to change the field name to a different format, you can change it using the following code:

const CREATED_AT = 'create_time';
const UPDATED_AT = 'update_time';
Copy the code

If you want to customize the timestamp format, you can set:

// Default format: 2021-01-30 14:23:51
// Use this if the database time is in timestamp format (seconds, e.g. 1612016648)
protected $dateFormat = 'U';
Copy the code

By default, the database connection configured in database. PHP is read. If this table is linked to another database, it can be changed locally on the model side:

protected $connection = 'mysql2';
Copy the code

6.3 Basic Usage of the Model (check)

1. In the previous section, we created a model that can be used directly.

For example, in UserController, say:

public function index()
{
    // Query all records
    $users = User::get(); / / or all ()
    return [$users];
}
Copy the code

You can query all user lists.

Note here that the introduced User is from the App Models Models User directory.

2. However, before using the model, although we have installed the Laravel plug-in, there is still no code hint, so we can solve this problem by following other plug-ins:

composer require barryvdh/laravel-ide-helper
Copy the code

Then, run the following commands one by one (generally, you can run the first two commands) :

PHP artisan ide-helper:generate -- generate annotations for Facades -- PHP artisan ide-Helper :models -- Generate annotations for data models -- PHP artisan ide-Helper :meta -- Generate PhpStorm Meta fileCopy the code

After that, there’s a hint!

3. Model queries, like constructor queries, can add a variety of conditions, written in the same way:

public function index()
{
    // Select * from 'male' where 'price' > 90
    $users = User::where([
        ['gender'.'='.'male'],
        ['price'.'>'.95]
    ])->limit(2)->get();
    return [$users];
}
Copy the code

You can also use the toSql() method to enter the SQL statement to execute:

public function index()
{
    // Select * from 'male' where 'price' > 90
    $users = User::where([
        ['gender'.'='.'male'],
        ['price'.'>'.95]
    ])->limit(2)->toSql();
    return [$users];
}
Copy the code

The execution result is:

select * from `laravel_users` where (`gender` = ? and `price` >?). limit2
Copy the code

4, other query methods are basically the same as the query constructor, if there are different, refer to the error message to modify. The main methods are:

.find(1) 				// Search by primary key
.first() 				// Look for the first one
.firstWhere() 			// Find the first one in the query
.find([1.2.3]) 			// Search by array
.firstOr() 				// Find the first return, support closures
.firstOrFail() 			// Return an exception if it is not found.count(), Max (), etc// Set operation
Copy the code

Many other methods in the query constructor, such as sorting, grouping subqueries, and so on, can be used (without verifying each one)

6.4 Addition, deletion and modification of the model

6.4.1 new

The methods added to the model are as follows:

public function index()
{
    $users = new User();
    $users->username = 'Joe';
    $users->password = '123456';
    $users->email = '[email protected]';
    $users->details = '123321';
    $users->save();
// return [$users];
}
Copy the code

In addition, you can use the create() method to add

User::create([
    'username'= >'Joe'.'password'= >'123456'.'email'= >'[email protected]'.'details'= >'123321',]);Copy the code

If executed directly, an error will be reported:

This requires setting the license for batch assignment on the model side:

class User extends Model
{
    // License batch assignment (default no assignment)
    protected $fillable = [
        'username'.'password'.'email'.'details'
    ];
}
Copy the code

Then execute again, and the data can be added successfully.

As opposed to permission, there are operations that cannot be assigned:

$fillable; $fillable; $fillable
protected $guarded = ['uid'];
Copy the code

If you are in a development environment, you can remove the restriction on batch assignment:

// If the batch assignment limit is removed, go straight to the following
protected $guarded = [];
Copy the code

6.4.2 update

When you update the data, you can find a data by the primary key, modify the data, and update it (only these columns are modified) :

$users = User::find(102);
$users->username = 'bill';
$users->email = '[email protected]';
$users->save();
Copy the code

In addition, batch updates can be implemented using the update() method:

User::where('username'.'Joe')
    ->update([
        'username'= >'bill'.'email'= >'[email protected]'
    ]);
Copy the code

6.4.3 delete

Delete (); delete();

$users = User::find(102);
$users->delete();// There may be exceptions to handle
Copy the code

Can be deleted in batches:

// Delete in batches
$users = User::where('username'.'Joe');
$users->delete();
Copy the code

If you delete by primary key ID, use the destroy(id) method to eliminate query operations.

// Delete by primary key
User::destroy(102);

// Delete in batches by primary key
User::destroy([103.104.105]);
Copy the code

6.5 Batch assignment of models

For example, the data requested in the preceding paragraph looks like this:

http:/ / 127.0.0.1:8000 / user/index? The username = zhang SAN & password=123456&age=1024&[email protected] & details from ABC = = 123321 & 1231
Copy the code

From this link, we can see that some data has no matching fields in the database table.

So, on the Controller layer, use the \Request::all() method to retrieve the data handed in by the front end:

public function index()
{
    dd(\Request::all());
}
Copy the code

The execution result is:

array:6 [▼
  "username"= >"Zhang"
  "password"= >"123456"
  "age"= >"1024"
  "email"= >"[email protected]"
  "details"= >"123321"
  "abc"= >"1231"
]
Copy the code

It’s actually an array.

In the previous section, we saw that the addition, implemented through the create() method, takes an array as an argument and permits batch assignments in the template.

Therefore, you can use the following method to directly implement the new, not in the license data, directly filter out:

// Add data at one time through the submitted data
User::create(\Request::all());
Copy the code

Or write this:

public function index(Request $request)
{
// dd($request->all());
    User::create($request->all());
}
Copy the code

If a parameter is licensed but is not submitted, the addition will fail

6.6 Soft Deletion of models (Logical Deletion)

6.6.1 Using soft Delete

1, what is soft delete? Compared to a real delete, a soft delete is not a real delete, it is just hidden by a delete field.

2. Before using the soft delete function, create a field deleted_at(default) in the database to determine whether the soft delete function is enabled.

3. By default, this field is null, indicating that it is not deleted. If data is written to the field (deletion time), the field is deleted.

4. How do I enable soft delete? The following Settings need to be made in the model:

class User extends Model
{
    // Enable the soft delete function
    use SoftDeletes;
}
Copy the code

5. When the soft delete function is enabled, the delete operation in the preceding paragraph will become the update operation, and assign a value to the delete_at field:

$users = User::find(106);
$users->delete();
// Or use:
User::destroy(106);
Copy the code

After the execution is complete, delete_at time when field 106 is written and deleted.

6.6.2 Querying Soft Deleted Data

1. After the soft delete function is enabled, the deleted data cannot be obtained through the normal query function, and it will be automatically hidden:

// Soft deleted data is not visible
$users = User::get();
return [$users];
Copy the code

It is also not possible to obtain data that has been soft deleted separately:

// It is not possible to obtain the soft deleted data separately
$users = User::find(82);
return [$users];
Copy the code

The result returned is NULL.

2. If you want to query data that contains soft deleted data, use the withTrashed() method:

// Get the data that contains the soft delete
$users = User::withTrashed()->get();
return [$users];

// Retrieve the data that was soft deleted (even if it was not soft deleted)
$users = User::withTrashed()->find(82);
return [$users];
Copy the code

3. If you only want to search for the soft deleted data, use the onlyTrashed() method.

// Get all soft deleted data
$users = User::onlyTrashed()->get();
return [$users];

// Retrieve a soft deleted data (only soft deleted data can be searched)
$users = User::onlyTrashed()->find(82);
return [$users];
Copy the code

If the data is soft deleted, use trashed(). If the data is soft deleted, use trashed().

// Check whether the data is soft deleted
$users = User::withTrashed()->find(81);
return $users->trashed();
Copy the code

6.6.3 Restoring Soft Deleted Data

If you want to restore soft deleted data to normal (similar to restoring from the recycle bin), use the restore() method;

// Restore the soft deleted data to normal
$users = User::onlyTrashed()->find(82);
$users->restore();
Copy the code

6.6.4 Permanent Deletion after soft Deletion

Use the forceDelete() method if soft delete is enabled and you need to force a real permanent delete.

// Enable real permanent delete when soft delete is enabled
$users = User::onlyTrashed()->find(82);
$users->forceDelete();
Copy the code

The above.