Laravel Framework-eloquentorm Basic Section detailed

Source: Internet
Author: User
Tags bulk insert
Eloquent ['eləkwənt], the method of the database query constructor is also used for the model class, which is simply omitted DB::table(' Table name ') section.

Use the protected member variable $table in the model to specify the table name of the binding.

<?phpnamespace app;use illuminate\database\eloquent\model;class Flight extends model{    /**     * the table associated with the model.     *     * @var String */    protected $table = ' my_flights ';}

EloquentAssuming that each table has a primary key named ID, you can $primaryKey override the field name through the member variable, and assume that the Eloquent primary key field is an integer that is self-increasing, and if you want to use a non-self-increment primary key or a non-numeric primary key, you must specify that the property in the model is public $incrementing false.
By default, the Eloquent expected table exists created_at and updated_at two fields, the field type is timestamp , if you do not want both fields, set $timestamps tofalse

<?phpnamespace app;use illuminate\database\eloquent\model;class Flight extends model{    /**     * indicates if The model should be timestamped.     *     * @var BOOL */public    $timestamps = false;    /**     * The storage format of the model ' s date columns.     *     * @var String */    protected $dateFormat = ' U ';}

Use protected $connection = ' connection-name ' to specify the database connection used by the model.

Inquire

Basic Query Operation #
Method All is used to return all results in the model table

$flights = Flight::all (); foreach ($flights as $flight) {    echo $flight->name;}

You can also use get methods to add constraints to query results

$flights = App\flight::where (' active ', 1)     ->orderby (' name ', ' desc ')     ->take ()     ->get ();

As you can see, the method of the query constructor is also available for model classes

In the eloquent ORM, get and the all method queries out multiple result sets, their return values are an Illuminate\Database\Eloquent\Collection object that provides several ways to manipulate the result set

Public function Find ($key, $default = null);p ublic function contains ($key, $value = null);p ublic function Modelkeys ();p UBL IC function diff ($items) ...

There are a number of ways to do this, and here are just a few, more ways to refer to the API documentation Collection and usage documentation. The chunk method is also used to segment a large number of results.

Flight::chunk ($, function ($flights) {    foreach ($flights as $flight) {        //    }});

Querying single results

Use find and first methods to query a single result, returning a single instance of the model

Query model by PRIMARY key ... $flight = App\flight::find (1);//Use constraints ... $flight = App\flight::where (' active ', 1)->first ();

The use find method can also return multiple results, Collection returned as an object, with multiple primary keys

$flights = App\flight::find ([1, 2, 3]);

If the query is not the result, you can use findOrFail or firstOrFail method, these two methods will throw an exception when the query is not the result Illuminate\Database\Eloquent\ModelNotFoundException

$model = App\flight::findorfail (1), $model = app\flight::where (' legs ', ' > ', ')->firstorfail ();

If this exception is not caught, Laravel will automatically return a 404 response to the user, so if you want to return 404 if you cannot find it, you can return it directly using the method.

Route::get ('/api/flights/{id} ', function ($id) {    return app\flight::findorfail ($id);});

Query aggregate function results

As with query constructor query methods, you can use aggregate functions to return results, such as Max, Min,avg,sum,count, and so on.

$count = App\flight::where (' active ', 1)->count (); $max = App\flight::where (' active ', 1)->max (' price ');

Paging Query

Paged queries can use the Paginate function directly

Lengthawarepaginator paginate (     int $perPage = NULL,     array $columns = Array (' * '),     string $pageName = ' Page ', C3/>int|null $page = null)

Parameter description
Parameter type description
perpage int Display quantity per page
Columns column names for array queries
PageName String Page parameter name
page int current page number

The return value is the LengthAwarePaginator object.

$limit = £ º $page = 1;return Enterprise::p aginate ($limit, [' * '], ' page ', $page);

Insert

Basic Insert Operation #

Insert new data just create a new model instance, set the model properties, and finally call the Save method to

$flight = new Flight; $flight->name = $request->name; $flight->save ();

When you call the Save method, the timestamp is automatically set for the Created_at and Updated_at fields, and you do not need to manually specify

Bulk Assignment Insertion #

Use a create method to perform a bulk insert operation that assigns a value to a property of the model, which will return the newly inserted model, create specifying and attributes in the model before executing the method, fillable guarded to prevent illegal property assignment (for example, to avoid user- is_admin passed Attribute was mistakenly entered into the data table).

The purpose of the specified $fillable property is that the field specified by the property can be inserted by means of the create method, and the other fields will be filtered out, similar to the whitelist, and $guarded vice versa, similar to the blacklist.

protected $fillable = [' name '];//orprotected $guarded = [' Price '];

The create operation only has a whitelist or blacklist field that can be updated.

$flight = app\flight::create ([' name ' = ' Flight 10 ']);

In addition to the Create method, there are two other two ways to use Firstornew and firstorcreate.

firstOrCreatemethod is used to record the query with the given column value, and if it is not found, inserts a new. fristOrNewUnlike firstOrCreate similar, the difference is that if it does not exist, it returns a new model object, but the model is not persisted and requires a manual call to the Save method to persist to the database.

Use the property to retrieve flight, if it does not exist create ... $flight = app\flight::firstorcreate ([' name ' = ' Flight 10 ']);//use attribute to retrieve flight, Create a model instance if it does not exist ... $flight = app\flight::firstornew ([' name ' = ' Flight 10 ']);

Update

Basic Update Operation #

Method save not only can be used to insert new data, can also be used to update the data, just use the model method to query out the data to be updated, set the Model property to a new value, and then save can be updated, the Updated_at field will be updated automatically.

$flight = App\flight::find (1); $flight->name = ' New flight name '; $flight->save ();

You can also update multiple results by using the Update method

App\flight::where (' active ', 1)    ->where (' Destination ', ' San Diego ')    ->update ([' delayed ' = 1]);

Delete

Basic Delete Operation #
Using delete methods to delete a model

$flight = App\flight::find (1); $flight->delete ();

The above method needs to query out the model object first, then delete, or you can delete the model directly using the primary key without querying, using the Destroy method

App\flight::d Estroy (1); App\flight::d Estroy ([1, 2, 3]); App\flight::d Estroy (1, 2, 3);

Delete by using constraints, returns the number of rows deleted

$deletedRows = App\flight::where (' active ', 0)->delete ();

Soft Delete

Soft deletion is the addition of the Deleted_at field in the table, when the record is deleted, the record is not deleted, but the timestamp of the field is set, and the data for that field is masked by the eloquent model.

To enable soft deletion, you can reference the Illuminate\database\eloquent\softdeletes trait in the model and add the Deleted_at field to the dates property.

<?phpnamespace App;use Illuminate\database\eloquent\model;use Illuminate\database\eloquent\softdeletes;class Flight extends model{use    softdeletes;    /**     * The attributes that should is mutated to dates.     *     * @var array */    protected $dates = [' Deleted_at '];}

To determine if a model has been soft-deleted, you can use the trashed method

if ($flight->trashed ()) {    //}

Querying soft-deleted models #

Model with soft-deleted #

If the model is soft deleted, the normal query will not query the result, you can use the Withtrashed method to force return the results of soft deletion

$flights = app\flight::withtrashed ()      ->where (' account_id ', 1)      ->get ();//can also be used in associated operations $flight-> History ()->withtrashed ()->get ();

Querying soft-deleted models only #

$flights = app\flight::onlytrashed ()      ->where (' airline_id ', 1)      ->get ();

To restore a soft-deleted model #

After you query to a soft-deleted model instance, call the Restore method to revert

$flight->restore ();

can also be used in queries

App\flight::withtrashed ()    ->where (' airline_id ', 1)    ->restore ();//The $flight->history () can also be used in the associated operation ()- >restore ();

Force Delete (persist delete) #

Force deleting a single model instance ... $flight->forcedelete ();//force deleting all related models ... $flight History ()->forcedelete ();

After the above operation, the data will be deleted by the real.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.