Eloquent ORM筆記


基本操作

新增

$user = new User;
$user->name = 'John';
$user->save();
$insertedId = $user->id;//從對象取得 id 屬性值

使用模型的 Create 方法

class User extends Model {
    protected $guarded = ['id', 'account_id'];//黑名單,不會被更新
}

// 在數據庫中建立一個新的用戶...
$user = User::create(['name' => 'John']);

// 以屬性找用戶,若沒有則新增並取得新的實例...
$user = User::firstOrCreate(['name' => 'John']);

// 以屬性找用戶,若沒有則建立新的實例...
$user = User::firstOrNew(['name' => 'John']);

刪除

$this->where($where)->delete();

或者
$user = User::find(1);
$user->delete();

更新

return $this->where($where)->update($data);

或者
$user = User::find(1);
$user->update($data);

查找

//取出所有記錄,all()得出的是對象集合,可以遍歷
$this->all()->toArray();

//根據主鍵取出一條數據
$one = $this->find('2');
return array(
  $one->id,
  $one->title,
  $one->content,
);

//查找id=2的第一條數據
$this->where('id', 2)->first()->toArray();

//查找id>0的所有數據
$this->where('id', '>', '0')->get()->toArray();

//查找id>0的所有數據,降序排列
$this->where('id', '>', '0')->orderBy('id', 'desc')->get()->toArray();

//查找id>0的所有數據,降序排列,計數
$this->where('id', '>', '0')->orderBy('id', 'desc')->count();

//offset,limit
$this->where('id', '>', '0')->orderBy($order[0], $order[1])->skip($offset)->take($limit);

//等同於
$this->where('id', '>', '0')->orderBy($order[0], $order[1])->offset($offset)->limit($limit);

更多:

//條件類:

where('id', '>', '0')
where('id', '>=', '0')
where('id', '<', '0')
where('id', '<=', '0')
where('id', 'like', 'name%')

whereIn($key, $array)
whereNotIn($key, $array)
whereBetween($key, $array)
whereNotBetween($key, $array)

orWhereIn($key, $array)
orWhereNotIn($key, $array)
orWhereBetween($key, $array)
orWhereNotBetween($key, $array)

//結果方法:Illuminate\Database\Query\Builder

first()取第一個
get()取所有
all()取所有(無條件)

//聚合方法
count()統計
avg()求平均值
sum()
max()
min()

Eloquent ORM - Laravel 中文文檔
http://laravel-china.org/docs/5.0/eloquent


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM