简介eloquent 为laravel中的orm模块
以下代码为orm对象生成命令
php artisan make:model Flight //创建Flight orm 对象
php artisan make:model Flight --migration | -m //生成migration数据库迁移文件
# Generate a model and a FlightFactory class...
php artisan make:model Flight --factory
php artisan make:model Flight -f
# Generate a model and a FlightSeeder class...
php artisan make:model Flight --seed
php artisan make:model Flight -s
# Generate a model and a FlightController class...
php artisan make:model Flight --controller
php artisan make:model Flight -c
# Generate a model and a migration, factory, seeder, and controller...
php artisan make:model Flight -mfsc
生成的基本对象:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
//optional
protected $table = 'my_flights';//指定表名
protected $primaryKey = 'flight_id'; //指定主键
public $incrementing = false; //主键生成模式
protected $keyType = 'string';
//主键数据类型
public $timestamps = false;
//是否有create 和 update 时间
protected $dateFormat = 'U';
//日期格式
const CREATED_AT = 'creation_date';
//创建时间字段名
const UPDATED_AT = 'updated_date';//更新时间字段名
protected $connection = 'sqlite';
//指定该orm数据库连接
protected $fillable = [] //数组 可批量创建的字段
protected $guard = [] //数组 不可批量创建的字段
protected $attributes = [
//字段默认值
'delayed' => false,
];
}
查询方法:
Flight::all
use App\Models\Flight;
foreach (Flight::all() as $flight) {
echo $flight->name;
}
查询构造器
$flights = Flight::where('active', 1)
->orderBy('name')
->take(10)
->get();
聚合函数
$count = Flight::where('active', 1)->count();
$max = Flight::where('active', 1)->max('price');
对象collection reject方法剔除取消的航班 (闭包返回true)
$flights = Flight::where('destination', 'Paris')->get();
$flights = $flights->reject(function ($flight) {
return $flight->cancelled;
});
orm游标
use App\Models\User;
$users = User::cursor()->filter(function ($user) {
return $user->id > 500;
});
子查询
use App\Models\Destination;
use App\Models\Flight;
return Destination::addSelect(['last_flight' => Flight::select('name')
->whereColumn('destination_id', 'destinations.id')
->orderByDesc('arrived_at')
->limit(1)
])->get();
查一条数据
use App\Models\Flight;
// Retrieve a model by its primary key...
$flight = Flight::find(1);
// Retrieve the first model matching the query constraints...
$flight = Flight::where('active', 1)->first();
// Alternative to retrieving the first model matching the query constraints...
$flight = Flight::firstWhere('active', 1);
查到一条或者(闭包)
model = Flight::where('legs', '>', 3)->firstOr(function () {
// ...
});
查询报notFound fail方法
$flight = Flight::findOrFail(1);
$flight = Flight::where('legs', '>', 3)->firstOrFail();
静态创建
use App\Models\Flight;
// Retrieve flight by name or create it if it doesn't exist...
$flight = Flight::firstOrCreate([
'name' => 'London to Paris'
]);
// Retrieve flight by name or create it with the name, delayed, and arrival_time attributes...
$flight = Flight::firstOrCreate(
['name' => 'London to Paris'],
['delayed' => 1, 'arrival_time' => '11:30']
);
// Retrieve flight by name or instantiate a new Flight instance...
$flight = Flight::firstOrNew([
'name' => 'London to Paris'
]);
// Retrieve flight by name or instantiate with the name, delayed, and arrival_time attributes...
$flight = Flight::firstOrNew(
['name' => 'Tokyo to Sydney'],
['delayed' => 1, 'arrival_time' => '11:30']
);
对象创建
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\Flight;
use Illuminate\Http\Request;
class FlightController extends Controller
{
/**
* Store a new flight in the database.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// Validate the request...
$flight = new Flight;
$flight->name = $request->name;
$flight->save();
}
}
对象更新
use App\Models\Flight;
$flight = Flight::find(1);
$flight->name = 'Paris to London';
$flight->save();
批量更新
Flight::where('active', 1)
->where('destination', 'San Diego')
->update(['delayed' => 1]);
对象填充数据
$flight->fill(['name' => 'Amsterdam to Frankfurt']);
按条件更新或创建
$flight = Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],//条件
['price' => 99, 'discounted' => 1] //数据
);
Flight::upsert([
['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99],
['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150]
], ['departure', 'destination'], ['price']);
删除
use App\Models\Flight;
$flight = Flight::find(1);
$flight->delete();
Flight::destroy(1);
Flight::destroy(1, 2, 3);
Flight::destroy([1, 2, 3]);
Flight::destroy(collect([1, 2, 3]));
查询删除
$deletedRows = Flight::where('active', 0)->delete();
逻辑删除
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Flight extends Model
{
use SoftDeletes; //多一个deleted_at字段
}
迁移文件
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Facades\Schema;
Schema::table('flights', function (Blueprint $table) {
$table->softDeletes();
});
Schema::table('flights', function (Blueprint $table) {
$table->dropSoftDeletes();
});
检查是是否被软删除
if ($flight->trashed()) {
//
}
还原逻辑删除的数据
$flight->restore();
Flight::withTrashed()
->where('airline_id', 1)
->restore();
$flight->history()->restore();
强制物理删除
$flight->forceDelete();
和软删除的数据一起查询
$flights = Flight::withTrashed()
->where('account_id', 1)
->get();
只查询软删除的数据
$flights = Flight::onlyTrashed()
->where('airline_id', 1)
->get();
对象复制replicate
use App\Models\Address;
$shipping = Address::create([
'type' => 'shipping',
'line_1' => '123 Example Street',
'city' => 'Victorville',
'state' => 'CA',
'postcode' => '90001',
]);
$billing = $shipping->replicate()->fill([
'type' => 'billing'
]);
$billing->save();