阅读Laravel5.1的手册时,发现有些地方没有翻译完成,还是英文状态。为了加深对Laravel的Eloquent的认识,总结了一些入门Eloquent的地方,大部分代码摘自手册,都做了注释:
Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model {
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'my_flights'; //默认情况下模型名的复数形式(+s)为数据表名,也可以为模型指定表名
protected $primaryKey = 'filght_id'; //默认情况下使用'id'作为表主键,也可以指定主键名
public $timestamps = false; //默认情况下,Eloquent 期望数据表中存在 created_at 和 updated_at 字段。也可以取消
protected $dateFormat = 'U'; //定制时间戳的格式
protected $fillable = ['first_name', 'last_name', 'email']; //定义允许批量更新的字段白名单
protected $guarded = ['id', 'password']; //定义不允许更新的字段黑名单
public function scopePopular($query) {
return $query->where('votes', '>', 100);
}
public function scopeWomen($query) {
return $query->whereGender('W');
}
//在controller中,使用$users = Flight::popular()->women()->orderBy('created_at')->get();可以自定义查询范围
}
Controller:
<?php
namespace App\Http\Controllers;
use App\Flight;
use App\Http\Controllers\Controller;
class FlightController extends Controller {
//查询所有记录
public function all() {
$flights = Flight::all(); //取出flights表的所有数据
foreach ($flights as $flight) {
echo $flight->name; //获取列的值
}
return view('flight.index', ['flights' => $flights]);
}
//多种查询条件:where, order by, limit
public function select() {
$flights = App\Flight::where('active', 1)
->orderBy('name', 'desc')
->take(10)
->get();
}
//当查询结果有大量数据时,使用分块查询能节省内存资源
public function chunkSelect() {
Flight::chunk(200, function ($flights) {
foreach ($flights as $flight) {
echo $flight->name;
}
});
}
//查询一条记录
public function find() {
$flight = App\Flight::find(1); //根据主键值1查找数据。
$flight = App\Flight::where('active', 1)->first(); //根据where查询符合条件第一条记录
//如果下面的查询方法未查到数据,则会抛出404错误
$model = App\Flight::findOrFail(1);
$model = App\Flight::where('legs', '>', 100)->firstOrFail();
}
//统计查询
public function Aggregates() {
$count = App\Flight::where('active', 1)->count();
$max = App\Flight::where('active', 1)->max('price');
}
//插入一条数据
public function insert(Request $request) {
$flight = new Flight;
$flight->name = $request->name;
$flight->save(); //向数据库中插入一条记录,name字段的值为表单传递的name
}
//为了更新一条数据,首先你必须从数据库中将其取出,然后为需要更新的属性赋值,最后调用save方法
public function save() {
$flight = App\Flight::find(1);
$flight->name = 'New Flight Name';
$flight->save();
}
//限定where添加更新数据
public function update() {
App\Flight::where('active', 1)
->where('destination', 'San Diego')
->update(['delayed' => 1]);
}
//不存在则插入一条记录
public function firstOrCreate() {
$flight = App\Flight::firstOrCreate(['name' => 'Flight 10']); //如果不存在name为Flight 10,则插入一条
}
//删除时,先获取这条记录,然后delete
public function delete(){
$flight = App\Flight::find(1);
$flight->delete();
App\Flight::destroy(1); //删除主键为1的记录
App\Flight::destroy([1, 2, 3]); //删除主键为1,2,3的记录
$deletedRows = App\Flight::where('active', 0)->delete(); //删除active为0的数据
}
//软删除:并不物理删除数据,只是添加删除字段delete_at
public function softDelete() {
/**
*调用 delete 方法时, deleted_at字段会被更新成现在的时间戳。在查询使用软删除功能的模型时,被「删除」的模型数据不会出现在查询结果里。
*
* 需要在对应的model中,设置
* use Illuminate\Database\Eloquent\SoftDeletes;
* use SoftDeletes;
* protected $dates = ['deleted_at'];
*
* 在migration中,生成这个字段
* Schema::table('flights', function ($table) {$table->softDeletes();});
*
* 执行删除时使用delete方法即可。
*
* 判断某个模型数据,是否已删除:
* $flight = Flight::find(1);
* if ($flight->trashed()) {...}
*/
}
//查询已删除的,account_id为1的数据
public function selectTrashed() {
$flights = App\Flight::withTrashed()
->where('account_id', 1)
->get();
}
//同上
public function selectOnlyTrashed() {
$flights = App\Flight::onlyTrashed()
->where('airline_id', 1)
->get();
}
//恢复软删除的数据
public function resoreTrashed() {
//法1
$flight = \App\Flight::find(1);
$flight->restore();
//法2
Flight::withTrashed()->where('account_id', 1)->restore();
}
//彻底删除数据(物理清除软删除的数据)
public function forceDelete() {
$flight = \App\Flight::find(1);
$flight->forceDelete();
}
//多重where条件查询含有软删除的数据,需注意查询需不需要group
public function selectClauseTrashed() {
User::where(function($query) {
$query->where('name', '=', 'John')->orWhere('votes', '>', 100);
})->get();
//select * from `users` where `users`.`deleted_at` is null and (`name` = 'John' or `votes` > 100)
User::where('name', '=', 'John')->orWhere('votes', '>', 100)->get();
//select * from `users` where `users`.`deleted_at` is null and `name` = 'John' or `votes` > 100
}
}