Eloquent基礎用法
一、創建usermodel
執行命令:
php artisan make:model user
二、app目錄下出現User.php
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $primaryKey='user_id';//設置主鍵為"user_id",默認為"id"
protected $guarded = ['user_id'];//設置user_id字段不可以被重寫
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [//執行查詢不會顯示的字段
'password', 'remember_token',
];
public function userTest(){
// return $this->find(5);//查找主鍵為“5”的數據,不存在返回空
// return $this->findOrFail(5);//查找主鍵為“5”的數據,不存在會報錯
// return $this->where('username','郭慶')->get();//查找用戶名為郭慶的數據
// return $this->where('user_id','>','1')->get();//查找id大于1的數據
}
}
三、在入口文件調用
Route::get('mysql',function(){
$user=new App\User();
return $user->userTest();
});
四、數據的增刪改
-
增
直接添加數據
public function userAdd(){ $this->username='lisi'; $this->age=13; $this->save(); }
使用數組添加數據
public function userAdd(){ $data=['username'=>'撒媳婦','age'=>100]; $this->fill($data);//填充數據 $this->save(); }
-
刪
單條刪除:
public function userDelete(){ $users=$this->find(10); $users->delete(); }
批量刪除:
public function userDelete(){ $users=$this->where('age','<',30); $users->delete(); }
-
改
單條修改:
public function userUpdate(){ $user=$this->find(5); $user->username='sb'; $user->age=29; $user->save(); }
批量修改:
public function userUpdate(){ $users=$this->where('age','<',30); $users->update(['username'=>'小屁孩']); }
五、集合
$arr=['one'=>1,2,3,4,5];
$collection=collect($arr);
$r=$collection->contains('one');//判斷是否有這個值
$r=$collection->has('one');//判斷是否有這個鍵
$r=$collection->take(2);//取出前倆個值
$r=$collection->take(-2);//取出后倆個值
return $r?'有':'沒有';
其余方法參見手冊:
https://laravel.com/docs/5.3/collections