轉載自 Laravel-newsphp
//常規寫法
$article = Article::find($article_id);
$article->read_count++;
$article->save();
//eloquent寫法-1
$article = Article::find($article_id);
$article->increment('read_count');
//eloquent寫法-2 鏈式寫法
Article::find($article_id)->increment('read_count');
Article::find($article_id)->increment('read_count', 10); // +10
Product::find($produce_id)->decrement('stock'); // -1
複製代碼
XorY methods
findOrFail()
: 查詢不到的時候直接報錯$user = User::find($id);
if (!$user) { abort (404); }
//以上代碼等同於
$user = User::findOrFail($id);
複製代碼
firstOrCreate()
:使用給定的字段及其值在數據庫中查找記錄。若是在數據庫中找不到模型,則將使用第一個參數中的屬性以及可選的第二個參數中的屬性插入記錄// 經過 name 屬性檢索航班,當結果不存在時建立它...
$flight = App\Flight::firstOrCreate(['name' => 'Flight 10']);
// 經過 name 屬性檢索航班,當結果不存在的時候用 name 屬性和 delayed 屬性去建立它
$flight = App\Flight::firstOrCreate(
['name' => 'Flight 10'], ['delayed' => 1]
);
複製代碼
firstOrNew()
:用法和firstOrCreate()
同樣,可是firstOrNew()
只是實例化一個對象,若是須要持久化則須要save()
保存updateOrCreate()
: 更新現有模型或建立新模型(若是不存在),同firstOrCreate()
Model
類boot()
方法/** * 基類:新增的時候自動將`uuid`字段用`Uuid`生成器填充 */
class BaseModel extends Model {
public static function boot() {
parent::boot();
self::creating(function ($model) {
$model->uuid = (string)Uuid::generate();
});
}
}
/** * 用戶模型:修改的時候設置額外的操做 */
class User extends BaseModel {
public static function boot() {
parent::boot();
static::updating(function($model) {
// do some logging
// override some property like $model->something = transform($something);
});
}
}
複製代碼
Relationship with conditions and ordering
//一般的作法,關聯用戶模型
public function users() {
return $this->hasMany('App\User');
}
//關聯已經批准並用`email`排序的用戶模型
public function approvedUsers() {
return $this->hasMany('App\User')->where('approved', 1)->orderBy('email');
}
複製代碼
Model
類屬性 Model properties: timestamps, appends etc.
class User extends Model {
//常常用到的屬性
protected $table = 'users';
protected $fillable = ['email', 'password']; // which fields can be filled with User::create()
protected $dates = ['created_at', 'deleted_at']; // which fields will be Carbon-ized
protected $appends = ['field1', 'field2']; // additional values returned in JSON
//其餘頗有用的屬性
protected $primaryKey = 'uuid'; // it doesn't have to be "id"
protected $keyType = 'string'; //設置主鍵字段類型 default `int`
public $incrementing = false; // and it doesn't even have to be auto-incrementing!
protected $perPage = 25; // Yes, you can override pagination count PER MODEL (default 15)
const CREATED_AT = 'created_at';
const UPDATED_AT = 'updated_at'; // Yes, even those names can be overridden
public $timestamps = false; // or even not used at all
}
複製代碼
find
方法查找多條記錄Find multiple entries
//find經常使用用法
$user = User::find(1);
//find其實也接收 數組 爲參數
$users = User::find([1,2,3]);
複製代碼
whereX
魔術方法//where字段名:字段名第一字母大寫
$users = User::whereApproved(1)->get(); //等同於 $users = User::where('approved', 1)->get();
User::whereDate('created_at', date('Y-m-d'));
User::whereDay('created_at', date('d'));
User::whereMonth('created_at', date('m'));
User::whereYear('created_at', date('Y'));
複製代碼
Order by relationship
場景:論壇不少帖子
topic
,須要按有最新發言post
的來排序laravel
//帖子關聯最新的發言
public function latestPost() {
return $this->hasOne(\App\Post::class)->latest();
}
$users = Topic::with('latestPost')->get()->sortByDesc('latestPost.created_at');
複製代碼
Eloquent::when()
別再寫那麼多的if-else
//一般的寫法
if (request('filter_by') == 'likes') {
$query->where('likes', '>', request('likes_amount', 0));
}
if (request('filter_by') == 'date') {
$query->orderBy('created_at', request('ordering_rule', 'desc'));
}
//Eloquent::when()寫法
$query = Author::query();
$query->when(request('filter_by') == 'likes', function ($q) {
return $q->where('likes', '>', request('likes_amount', 0));
});
$query->when(request('filter_by') == 'date', function ($q) {
return $q->orderBy('created_at', request('ordering_rule', 'desc'));
});
//能夠傳遞參數
$query = User::query();
$query->when(request('role', false), function ($q, $role) {
return $q->where('role_id', $role);
});
$authors = $query->get();
複製代碼
BelongsTo Default Models
//blade:若是 author 被刪了就會報錯
{{ $post->author->name }}
//設置 缺省Model 避免以上錯誤
public function author() {
return $this->belongsTo('App\Author')->withDefault([
'name' => 'Guest Author'
]);
}
複製代碼
collect->sortBy
方法function getFullNameAttribute() {
return $this->attributes['first_name'] . ' ' . $this->attributes['last_name'];
}
//錯誤寫法
$clients = Client::orderBy('full_name')->get(); // doesn't work
//正確寫法,藉助collect的sortBy方法
$clients = Client::get()->sortBy('full_name'); // works!
複製代碼
protected static function boot() {
parent::boot();
// Order by name ASC
static::addGlobalScope('order', function (Builder $builder) {
$builder->orderBy('name', 'asc');
});
}
複製代碼
// whereRaw
$orders = DB::table('orders')
->whereRaw('price > IF(state = "TX", ?, 100)', [200])
->get();
// havingRaw
Product::groupBy('category_id')->havingRaw('COUNT(*) > 1')->get();
// orderByRaw
User::where('created_at', '>', '2016-01-01')
->orderByRaw('(updated_at - created_at) desc')
->get();
複製代碼
這是複製某條記錄最好的方法數據庫
$task = Tasks::find(1);
$newTask = $task->replicate();
$newTask->save();
複製代碼
Collect
集合方法:須要輸出大量記錄的時候用chunk
數組
User::chunk(100, function ($users) {
foreach ($users as $user) {
// ...
}
});
複製代碼
用
artisan
命令生成model
的時候一塊兒生成controller -r
、migration file
bash
php artisan make:model Company -mcr
複製代碼
save()
方法接收額外的參數app
$product = Product::find($id);
$product->updated_at = '2019-01-01 10:00:00';
$product->save(['timestamps' => false]);
複製代碼
//返回更新的記錄數
$result = $products->whereNull('category_id')->update(['category_id' => 2]);
複製代碼
where
參數分組//... WHERE (gender = 'Male' and age >= 18) or (gender = 'Female' and age >= 65) 的 Eloquent 寫法
$q->where(function ($query) {
$query->where('gender', 'Male')
->where('age', '>=', 18);
})->orWhere(function($query) {
$query->where('gender', 'Female')
->where('age', '>=', 65);
})
複製代碼
$q->orWhere(['b' => 2, 'c' => 3]);
複製代碼