Laravel using the eloquent ORM to manipulate the database

Source: Internet
Author: User

1. Defining the Model

<?php
namespace App;
Use Illuminate\database\eloquent\model;
class Flight extends model{
protected $table = ' my_flights ';
protected $primaryKey = ' my_id ';
Public $timestamps = false;
}

2. Get all the data in the table All/get

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

3.find and first get a single record

//
$flight = App\flight::find (1);

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

4. Get aggregations

$count = app\flight::where (' active ', 1),Count();
$max = app\flight::where (' active ', 1),Max(' Price ');

5. New

To insert a new record into the database, simply create a new model instance, set the properties of the model, and then call the Save method:

$flight New Flight;
$flight $request->name;
$flight->save ();

The Save method can also be used to update a model that already exists in the database. To update a model, you should get it, set the property you want to update, and then call the Save method.

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

The Create method inserts a new record into the database that returns the model instance that was inserted, first set up in the model:

Properties that can be assigned in bulk
Protected$fillable = [' name '];
$flight = app\flight::create ([' name ' = ' Flight 10 ']);

6. Delete

To delete a model, call the Delete method on the model instance:

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

If you know the primary key of the model, you can delete it directly without needing to get it:

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

Delete multiple models from a query

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

Laravel using the eloquent ORM to manipulate the database

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.