php Laravel Eloquent Tips

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php Laravel Eloquent Tips相关的知识,希望对你有一定的参考价值。


<?php
// ======= Increments and Decrements ========
// Instead of:
$article = Article::find($article_id);
$article->read_count++;
$article->save();


// Do:
$article = Article::find($article_id);
$article->increment('read_count');

// Also:
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  =============
// Instead of :
$user = User::find($id);
if (!$user) { abort (404); }

// Do: 
$user = User::findOrFail($id);

// Instead of:
$user = User::where('email', $email)->first();
if (!$user) {
  User::create([
    'email' => $email
  ]);
}

// Do:
$user = User::firstOrCreate(['email' => $email]);

// ======= Model Relationships ========

// Regular Relationships:
public function users() {
    return $this->hasMany('App\User');    
}

// You can also do this:
public function approvedUsers() {
    return $this->hasMany('App\User')->where('approved', 1)->orderBy('email');
}

// ====== Find, Where ========

// We can find a resource with:
$user = User::find(1);

// But we can also find multiple users:
$users = User::find([1,2,3]);

// Turn :
$users = User::where('approved', 1)->get();

// Into:
$users = User::whereApproved(1)->get(); 

// Predefined Eloquent date/times:
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'));


//  ======= Raw query Methods =========
// 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();

// ======== Replicate rows =======
// make a copy of database entry
$task = Tasks::find(1);
$newTask = $task->replicate();
$newTask->save();





以上是关于php Laravel Eloquent Tips的主要内容,如果未能解决你的问题,请参考以下文章

5 个 Laravel Eloquent 小技巧

php Laravel 5 Eloquent CheatSheet #laravel #eloquent

php Laravel 5 Eloquent CheatSheet #laravel #eloquent

php Laravel 5 Eloquent CheatSheet #laravel #eloquent

php [Eloquent CheatSheet] Eloquent #laravel #eloquent的常见查询方法

Laravel 的 Eloquent 公共静态函数“create”在 Model.php 中发生了啥?