Laravel add, delete, modify and check (AR mode)

1. Model operation (AR mode)

Laravel's own Eloquent ORM provides a beautiful and simple ActiveRecord implementation of database dealings. Each data table corresponds to a "Model model" that interacts with the table. The model allows you to query data in the table, as well as insert, Update, delete and other operations.

1. Each data table: Model mapping for interaction with the data table (instantiated model)
2. Fields in the record: mapping with the attributes of the model class (assign a value to the attribute, the field name is the attribute name)
3. In the table Each record: mapping with a complete request instance (specific CURD operation)

1. Define the model

(1) Define location:
Define the location of the model. The default is under the Models directory under the app directory.

(2) Naming rules
Laravel itself does not have strict requirements on the naming of the model, generally the table name (the first letter is capitalized)
. php For example: User.php, Goods.php

(3) Create a model.
You can use the artisan command: for example, create a member model [models can also be managed by directories]
php artisan make:model Member

Example:
Insert picture description here
Effect:
Insert picture description here
(4) Precautions for defining the model:

1. (Required) Define an $tableattribute whose value is the table name without prefix (the real table name). If it is not specified, the plural form of the class name will be used as the table name. If the model is a Member model without specifying the table attribute, it will find the members table by default. Modifier: protected
2. (Optional) Define the $primaryKeyattribute. The value is the primary key name. If you need to use the find method of AR mode, you may need to specify the primary key (Model::find(n)). When the primary key field is not id, then Need to specify the primary key, modifier: protected
3. (Optional) Define the $timestampsattribute, the value is false, if it is not set to false, the created_at and updated_at fields in the table will be operated by default. Generally, we do not have these two fields in the table, so Set to false, which means do not operate these two fields. Modifier: public.
4. (Optional) Define $fillableattributes, which indicate the field information that is allowed to be inserted into the database when using the model to insert data. The format is in the form of a one-dimensional array. Modifier: protected (it is best to use the create and save methods of the model) Write this attribute). Reverse specified attribute called: $guarded.

Two, call in the model controller

Introduce the Member model class:
Insert picture description here
the use of the model, there are two ways to use the model in the controller.
1. Directly use the same operation method as the DB facade: call static method as the main form, the model does not need to be instantiated in this form, for example: Member::get() is equivalent to DB::table('member') ->get();
2. Instantiate the model and then use the model class (normal)
For example: $model = new Member(); $model -> get();

Two forms of selection criteria:
if the methods used are all built in the laravel framework, choose arbitrarily;
if the method used is defined by the user in the model, use the second form.

Three, define the test route

Add: /mod_add
Delete: /mod_del
Change: /mod_mod
Check:/mod_select
Insert picture description here

3.1 Add data

There are two ways to add data in laravel:
Method 1 (AR mode): The model must be instantiated to use AR mode.
Note: When adding data in laravel, you need to instantiate the model first, and then set the attributes for the model. Finally, call the save method.

$member = new Member(); // Mapping relationship 1: Map the table to the model
$member -> name = value; // Mapping relationship 2: Map the field to the attribute, the attribute name and the field name are the same
$member -> age = value;

$member -> save(); // Mapping relationship 3: Mapping records to instances

Example:
Insert picture description here
Effect:
Insert picture description here
Insert picture description here
Method 2: (Hidden effect)
Create a simple form with fields for name, age, and email, which must be submitted.
Insert picture description here
Insert picture description here
First, introduce the Request class in the controller file
use Illuminate\Http\Request;(the framework itself has been introduced when creating the controller)

The use of the Request class
1. Object transfer, the Request class needs to be received in the form of formal parameters in the parentheses of the method, only the receiving class can be used in the method
2. Request syntax (similar to the input facade, the method name is the Insert picture description here
same, but the input call Is a static method, but the current one is not.)
$request->all() // Get all the data passed
$request->input('name') // Get the specified
$request->only(['name1', 'name2'])
$request->except(['name1','name2'])

Define fillable attribute:
Insert picture description here
controller code:
Insert picture description here
effect:
Insert picture description here
Insert picture description here

3.2 Query operation

Get a piece of data of the specified primary key
$info = Member::find(4);// Non-static method call to get data with a primary key of 4 [equivalent to the condition where id = 4]
The result set is an object by default.
Example:
Insert picture description here
Results:
Insert picture description here


If you want to get which one is direct:
Insert picture description here
Effect:
Insert picture description here


What is returned is not an array object, but a model object. If you need to convert the result set of the object into an array in laravel, you need to add a method call at the end: -> toArray()
Example:
Insert picture description here
Effect:
Insert picture description here


Query multiple rows and specify fields

Member::all(); // Query all data
Member::all([Field 1, Field 2]); // The difference with the get method, all does not support linking to other auxiliary query methods
Member::get()
Member::get([Field1, Field2])
Specify multiple fields in a conditional query
Member::where('id','>', '2') -> get(['Column1','Column2 ']); // Array selection column
Member::where('id','>', '2') -> select('column 1','column 2') -> get(); // string selected column
Member :: where ( 'id', '>', '2') -> select ([ ' column 1', 'column 2']) -> get ( ); // string selected rows

3.3 Modify data

If you need to update data in laravel (ORM model method), you need to call the find method of the model to get the corresponding record, return a model object, and then set the data to be updated (object properties) for the model object, and finally call the save method That's it.
For example:
$user= User::find( $id); // Query the record instance that needs to be modified
$user -> title = $_POST['title'];
$user -> content = $_POST['content'];
return $user -> save()?'OK':'fail';

Example: To implement the modification operation of the ORM formal model, the name of the user modified to 5 is Li Si:
Insert picture description here
Effect:
Insert picture description here
Insert picture description here

3.4 Delete data

Note: If you want to delete data in laravel, if you need to use AR mode to delete data, you must first query the corresponding record according to the primary key id, return a model object, and then call the delete method of the model object.
For example code:
$user= User::find( $id); // first query the record to be deleted
return $user -> delete() ? 'ok' : 'fail';// delete again

Example: Use AR mode to delete the record with id 6:
Insert picture description here
Effect:
Insert picture description here
Insert picture description here

On the way of learning php, if you think this article is helpful to you, then please pay attention to like and comment Sanlian, thank you, you must be another support for my blog.

Guess you like

Origin blog.csdn.net/weixin_44103733/article/details/113980336