laravel 模型
介绍
Laravel 的 Eloquent ORM 提供了漂亮、简洁的 ActiveRecord 实现来和数据库进行交互。每个数据库表都有一个对应的「模型」可用来跟数据表进行交互。
思路:每一个张创建一个模型,每一条数据就是一个对象
创建模型
php artisan make:model Order 模型文件默认存放的位置是在app目录下
php artisan make:model Order -m 这里会自动帮我们创建一个数据库迁移文件
模型限定
模型所对应的默认的表名是在模型后面加s, 如果模型名称后面有s,则表名跟模型名称同名.
eg:
Order => orders
Goods => goods
country => countries
主键字段 id
时间字段 created_at updated_at
属性设置
设置操作的表名
public $table = 'userinfos';
设置默认的时间字段
public $timestamps = false;
模型的日期字段保存格式。
protected $dateFormat = 'U';
修改默认的主键名称
public $primaryKey = 'uid';
数据操作
获取
取回单个模型
// 通过主键取回一个模型...
$flight = App\Flight::find(1);
// 取回符合查找限制的第一个模型 ...
$flight = App\Flight::where('active', 1)->first();
取回多个模型
$flights = Flight::all();
return view('flight.index', ['flights' => $flights]);
增加额外的限制
$flights = App\Flight::where('active', 1)
->orderBy('name', 'desc')
->take(10)
->get();
「未找到」异常
$model = App\Flight::findOrFail(1);
$model = App\Flight::where('legs', '>', 100)->firstOrFail();
如果没有捕捉到异常,则会自动地送回 HTTP 404 响应给用户,因此当使用这些方法时,你没有必要明确的编写检查来返回 404 响应:
Route::get('/api/flights/{id}', function ($id) {
return App\Flight::findOrFail($id);
});
取回集合
$count = App\Flight::where('active', 1)->count();
$max = App\Flight::where('active', 1)->max('price');
添加和更新模型
基本添加
// 验证请求...
$flight = new Flight;
$flight->name = '张三'
$flight->save();
基本更新
$flight = App\Flight::find(1);
$flight->name = 'New Flight Name';
$flight->save();
批量修改
update 方法会预计收到一个字段与值成对的数组,来代表应该被更新的字段
App\Flight::where('active', 1)
->where('destination', 'San Diego')
->update(['delayed' => 1]);
删除模型
基本删除
$flight = App\Flight::find(1);
$flight->delete();
通过键来删除现有的模型
App\Flight::destroy(1);
App\Flight::destroy([1, 2, 3]);
App\Flight::destroy(1, 2, 3);
通过查找来删除模型
$deletedRows = App\Flight::where('active', 0)->delete();
软删除/回收站
基本使用
1. 则必须在模型上使用 Illuminate\Database\Eloquent\SoftDeletes,并添加 deleted_at 字段到你的 $dates 属性上:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Flight extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
}?>
2. php artisan migrate:refresh
获取被软删除的模型
onlyTrashed 方法会 只 获取已被软删除的模型:
$flights = App\Flight::onlyTrashed()
->where('airline_id', 1)
->get();
恢复软删除的模型
你也可以在查找上使用 restore 方法来快速地恢复多个模型:
App\Flight::withTrashed()
->where('airline_id', 1)
->restore();
永久地删除模型
$flight->forceDelete();
关系
class User extends Model
{
//一对一
public function userinfo()
{
return $this->hasOne('App\Userinfo','user_id');
}
//属于
public function country()
{
return $this->belongsTo('App\Country','country_id');
}
//一对多
public function post()
{
return $this->hasMany('App\Post','user_id');
}
//多对多
public function group()
{
return $this->belongsToMany('App\Group','group_user','user_id','group_id');
}
}