Introduction to the eloquent model of Laravel

Source: Internet
Author: User
This article mainly introduces about Laravel's eloquent model introduction, has certain reference value, now shares to everybody, has the need friend can refer to

Eloquent model

The default inherits the use illuminate\database\eloquent\model class.

Data table name and model name conventions:

The table name of the database is typically named by the Serpentine nomenclature. The Serpentine nomenclature requires the words to be lowercase and the words to be concatenated with an underscore, and the name is plural.

The corresponding model name is named with the "Pascal method", which means that the first letter of the word is capitalized.

If you do not follow the above agreement, you need to indicate the corresponding data table:

Class Flight extends model{    /**     * Data table associated with model     *     * @var String *     /    protected $table = ' Myflights ';}

Primary key:

The Model default data table uses the ID field as the primary key and is the increment integer type. These can be customized:

Class Flight extends model{    /**     * Data table associated with the model */    protected $table = ' my_flights ';    Protected $primaryKey = ' mid ';  Custom primary key field        protected $keyType = ' string ';  The custom primary key type is string public        $incrementing = false;    Primary key non-self-increment}

Time Cut:

The model has the Created_at and Updated_at two fields by default, and you can set $timestamps without two fields:

Class Flight extends model{    /**     * Whether the model is automatically maintained timestamp */public    $timestamps = false;}

The $dateFormat property allows you to customize the format of the time-truncated format that is stored in the datasheet:

Class Flight extends model{    /**     * model's storage format for date fields */    protected $dateFormat = ' U ';}

Custom time Truncation Field name:

<?phpclass Flight extends model{    const CREATED_AT = ' creation_date ';    Const UPDATED_AT = ' last_update ';}

To customize a database connection:

Class Flight extends model{    /**     * Connection name for this model.     */    protected $connection = ' connection-name ';}

Model query:

Use app\flight; $flights = App\flight::all ();   Query all data foreach ($flights as $flight) {    echo $flight->name;} $flights = App\flight::where (' active ', 1)               ->orderby (' name ', ' desc ')               ->take ()               ->get ();             Conditionally querying data

The All and Get methods return Illuminate\database\eloquent\collection instances.

If you are querying large volumes of data, you can use chunk to save memory:

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

Or use the cursor method cursor significantly reduces memory usage:

foreach (Flight::where (' foo ', ' Bar ')->cursor () as $flight) {    //}

To query a single piece of data:

Retrieving a model from the primary key ... $flight = App\flight::find (1);//Retrieving the first model that meets the query limit ... $flight = app\flight::where (' active ', 1)->first ( )///If the model is not found, throws an exception//illuminate\database\eloquent\modelnotfoundexception//automatically returns an HTTP 404 response to the user $model = App\flight:: Where (' legs ', ' > ',->firstorfail ();

Aggregate query:

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

Data Update:

Save method: You need to retrieve the first time, then set the property to be updated and then execute the Save method, and Updated_at will update automatically.

Update method: Sets the Where condition, which updates the field with a key-value pair into the Update method. The update does not trigger saved and updated model events.

$flight = App\flight::find (1); $flight->name = ' New flight name '; $flight->save (); Query once and then update app\flight::where (' active ', 1)          ->where (' Destination ', ' San Diego ')          ->update ([' Delayed ' = > 1]); Set conditions and then batch update

Insert data:

To create data using a model, you first set the $fillable or $guarded property. Two properties can only be selected by two.

Class Flight extends model{    /**     * Properties that can be assigned in bulk.     * @var Array */    protected $fillable = [' name '];} Class Flight extends model{    /**     * Properties that cannot be assigned in bulk. can be defined as an empty array, which means that all properties can be assigned values.     * @var Array */    protected $guarded = [' Price '];}

Ways to insert data:

$flight = app\flight::create ([' name ' = ' Flight 10 ']); Add a new record and return the saved model instance $flight->fill ([' name ' = ' Flight 22 ']); An existing instance model can use the Fill method
Retrieve a flight through the Name property, create it when the result does not exist ... $flight = app\flight::firstorcreate ([' name ' = ' Flight 10 ']);//Retrieve Flight by Name property, when the result does not exist Use the Name property and the delayed property to create it $flight = App\flight::firstorcreate (    [' name ' = ' Flight '], [' delayed ' = + 1]);//Through The Name property retrieves the flight when the result does not exist instantiation ... $flight = app\flight::firstornew ([' name ' = ' = ' Flight 10 ']);//The flight is retrieved by the Name property, with the name when the result does not exist and delayed attribute instantiation $flight = app\flight::firstornew (    [' name ' = ' Flight '], [' delayed ' = + 1]);//If there is a flight from Oakland to Santiago class, set the price to $99//If no matching model exists, create a $flight = App\flight::updateorcreate (    [' departure ' = ' Oakland ', ' Destination ' =& Gt ' San Diego '],    [' price ' = 99]);

Firstorcreate: If the data is not found, the saved model is returned according to the first parameter and the second parameter record creation record;

Firstornew: If the data is not found, the new model is created according to the first parameter and the second parameter record, but the data is not saved and the data can be saved by manual save;

Updateorcreate: The first parameter is used to update the second parameter data, and if the data does not exist, merge two parameters to create the record to return the saved model.

To delete a model:

$flight = App\flight::find (1); $flight->delete ();  Delete method by querying the model instance deletes//deletes a maximum of data by primary key: App\flight::d Estroy (1); App\flight::d Estroy ([1, 2, 3]); App\flight::d Estroy (1, 2, 3);//Bulk Delete by query criteria and return the number of deleted bars $deletedrows = App\flight::where (' active ', 0)->delete ();

Deleted and deleting model events are not triggered when bulk deletion.

Soft Delete:

The data table should set the Deleted_at field. The model references softdeletes trait and sets the Deleted_at field to the $dates attribute.

<?phpnamespace App;use Illuminate\database\eloquent\model;use Illuminate\database\eloquent\softdeletes;class Flight extends model{use    softdeletes;    /**     * Attributes that need to be converted to a date.     * @var Array */    protected $dates = [' Deleted_at '];}

When a soft-deleted model is set, the Delete method sets Deleted_at to the current date and time. Querying a soft-deleted model automatically excludes soft-deleted models.

if ($flight->trashed ()) {//    checks if the model instance is soft-deleted} $flights = App\flight::withtrashed ()  //can use the query to contain soft-deleted data                - >where (' account_id ', 1)                ->get (); $flights = app\flight::onlytrashed ()  //query only soft-deleted data                ->where (' airline_id ', 1)                ->get (); $flight->restore ();  Recovering a soft-deleted model app\flight::withtrashed ()   //Batch recovery model does not trigger any model events        ->where (' airline_id ', 1)        ->restore ( );

The soft-delete model uses forced deletion:

$flight->forcedelete();

Query scope:

Adds a query constraint to the model. Both Global and Local:

Global--Each query automatically adds conditional constraints;

Local-invokes local constraints as needed.

Global scope:

First, you need to implement the scope interface class.

<?phpnamespace App\scopes;use Illuminate\database\eloquent\scope;use Illuminate\database\eloquent\model;use Illuminate\database\eloquent\builder;class Agescope implements scope{    /**     * Applies a range to a given eloquent query builder     *     * @param  \illuminate\database\eloquent\builder  $builder     * @param  \illuminate\database\ Eloquent\model  $model     * @return void     *    /Public Function apply (Builder $builder, Model $model)    {        return $builder->where (' Age ', ' > ', ')}    }

If the global scope is to add a field to the query's SELECT statement, you should use the addSelect method instead of theselect,以免替换查询的现有select。

Apply global scope:

The boot method of the model uses the Addglobalscope method.

<?phpnamespace app;use app\scopes\agescope;use illuminate\database\eloquent\model;class User extends Model{    / * * The     "Start" method of the Model     * * @return void */    protected static function boot ()    {        parent::boot ();        Static::addglobalscope (new Agescope);}    }

You can also use closures to define a global scope without having to define a class individually:

Class User extends model{    /**     * Model "Start" Method     * *     @return void *     /    protected static function Boot ()    {        parent::boot ();                Static::addglobalscope ("Age", Function (Builder $builder) {                    $builder->where (' Age ', ' > ', ')}}}    

To delete a global scope:

User::withoutglobalscope (Agescope::class)->get ();  Deletes the specified scope//Removes all global scopes user::withoutglobalscopes ()->get ();//Deletes some global scope user::withoutglobalscopes ([    Firstscope::class, Secondscope::class])->get ();

Local scope:

Defines a generic constraint to use when needed. Definition method: The method that defines the scope prefix within the model.

<?phpnamespace app;use illuminate\database\eloquent\model;class User extends model{    /**     * Limit query to include only popular users.     *     * @return \illuminate\database\eloquent\builder     *    /Public Function scopepopular ($query)    {        return $query->where (' votes ', ' > ');    }    /**     * Restrict queries to include only active users.     *     * @return \illuminate\database\eloquent\builder     *    /Public Function scopeactive ($query)    {        return $query->where (' active ', 1);}    }

How to use:

$users = App\user::p opular ()->active ()->orderby (' Created_at ')->get ();

Dynamic scope:

Class User extends model{    /**     * Restricts the query to include only users of the specified type.     *     * @return \illuminate\database\eloquent\builder     *    /Public Function Scopeoftype ($query, $type)    {        return $query->where (' type ', $type);}    } Call scope Shishun $users = app\user::oftype (' admin ')->get ();

Model events:

retrieved--Query Trigger

creatingcreated--创建触发

updatingupdated--更新触发

savingsaved--创建、更新触发

deletingdeleted--删除触发

restoringrestored--恢复触发

Event to assign the appropriate monitor:

<?phpnamespace app;use app\events\usersaved;use app\events\userdeleted;use illuminate\notifications\notifiable; Use Illuminate\foundation\auth\user as Authenticatable;class User extends authenticatable{use    notifiable;    /**     * The event map of the model.     *     * @var array */    protected $dispatchesEvents = [        ' saved ' = = Usersaved::class,   // Trigger saved event, call usersaved monitor        ' deleted ' + userdeleted::class,//Trigger deleted event, invoke userdeleted Monitor    ];}

All listeners can also be placed in an observer class:

<?phpnamespace app\observers;use app\user;class userobserver{    /**     * listens for user-created events.     *     * @param  user  $user     * @return void     *    /Public function created (user $user)    {        //    }    /**     * Listens for user delete events.     *     * @param  user  $user     * @return void     *    /Public Function deleting (user $user)    {        //    }}

Register Observer:

<?phpnamespace app\providers;use app\user;use app\observers\userobserver;use Illuminate\Support\ServiceProvider , class Appserviceprovider extends serviceprovider{    /**     * Run all apps.     *     * @return void */public    function boot ()    {        user::observe (userobserver::class);    } }

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

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.