Skip to content
Permalink
master
Switch branches/tags
Go to file
 
 
Cannot retrieve contributors at this time

ORM

鐩墠 PhpBoot 鎻愪緵鍩烘湰鐨 ORM 鏀寔锛屽寘鎷細

1. 瀹氫箟瀹炰綋

瀹炰綋瀵瑰簲鏁版嵁搴撶殑琛紝 瀹炰綋鐨勫睘鎬у悕鍜屾暟鎹簱鐨勫垪鍚嶄竴鑷淬備笅闈㈡槸涓涓吀鍨嬬殑瀹炰綋瀹氫箟锛

/**
 * 鍥句功淇℃伅
 * @table books
 * @pk id
 */
class Book
{
    /**
     * @var int
     */
    public $id;
    
    /**
     * 涔﹀悕
     * @var string
     */
    public $name='';
    
    /**
     * 鍥剧墖url
     * @var string[]
     */
    public $pictures=[];
}

鍏朵腑:

  • @table 鎸囧畾琛ㄥ悕
  • @pk 鎸囧畾琛ㄧ殑涓婚敭
  • @var 瀹氫箟鍒楃殑绫诲瀷锛屽鏋滅被鍨嬩负瀵硅薄鎴栬呮暟缁勶紝鍒欎繚瀛樺埌鏁版嵁搴撴槸灏嗚搴忓垪鍖栦负 json

鍙互鐪嬪埌锛孫RM 涓殑瀹炰綋鍜屾帴鍙d腑鐨勫疄浣撳緢绫讳技锛屼簨瀹炰笂锛屾垜浠榧撳姳鍦 ORM 鍜屾帴鍙d腑澶嶇敤瀹炰綋绫

2. 鎿嶄綔鏁版嵁搴

PhpBoot 鎻愪緵閲忎釜缁勬柟娉曪紝modelmodels, 鍒嗗埆鐢ㄤ簬鎿嶄綔瀹炰綋鈥滃疄渚嬧濆拰瀹炰綋鈥滅被鈥濄

2.1. model 鏂规硶

model() 鏂规硶鐢ㄤ簬鎿嶄綔瀹炰綋鈥滃疄渚嬧濓紝鎴栬呰鎿嶄綔鍗曚釜瀹炰綋瀵硅薄銆

2.1.1 create

瀛樺偍鎸囧畾瀹炰綋瀹炰緥锛堝搴 SQL 鐨 insert锛

$book = new Book();
$book->name = ...
...

\PhpBoot\model($this->db, $book)->create();
echo $book->id; //鑾峰彇鑷涓婚敭鐨勫

2.1.2 update

鏇存柊瀹炰綋瀵瑰簲鐨勬暟鎹簱璁板綍锛堝搴 SQL 鐨 update锛

$book = new Book();
$book->id = ...
...

\PhpBoot\model($this->db, $book)->update();

2.1.3 delete

鍒犻櫎瀹炰綋瀵瑰簲鐨勬暟鎹簱璁板綍锛堝搴 SQL 鐨 delete 锛

$book = new Book();
$book->id = ...

\PhpBoot\model($this->db, book)->delete();

2.2 models 鏂规硶

models() 鏂规硶鐢ㄤ簬鎿嶄綔瀹炰綋鈥滅被鈥濓紝鎴栬呰鎿嶄綔涓缁勫疄浣撱

2.2.1. find

鏍规嵁涓婚敭鏌ユ壘锛堝搴 SQL 鐨 select 锛

$book = \PhpBoot\models($this->db, Book::class)->find($id);

2.2.2. findWhere

鏍规嵁缁勫悎鏌ヨ鏉′欢鏌ユ壘锛堝搴 SQL 鐨 select 锛

$books = \PhpBoot\models($this->db, Book::class)
    ->findWhere(['name'=>'abc'])
    ->get();

2.2.3. update

鏍规嵁涓婚敭鏇存柊锛堝搴 SQL 鐨 update 锛

\PhpBoot\models($this->db, Book::class)
    ->update(1锛 ['name'=>'abc']);

2.2.4. updateWhere

鏍规嵁缁勫悎鏌ヨ鏉′欢鏇存柊锛堝搴 SQL 鐨 update 锛

\PhpBoot\models($this->db, Book::class)
    ->updateWhere(['name'=>'abc'], ['id'=>1])
    ->exec();

2.2.6. delete

鏍规嵁涓婚敭鍒犻櫎锛堝搴 SQL 鐨 delete 锛

\PhpBoot\models($this->db, Book::class)
    ->delete(1);

2.2.7. deleteWhere

鏍规嵁缁勫悎鏌ヨ鏉′欢鍒犻櫎锛堝搴 SQL 鐨 delete 锛

\PhpBoot\models($this->db, Book::class)
    ->deleteWhere(['id'=>1])
    ->exec();