> The sticky option is an optional value that can be used to allow the immediate reading of records that have been written to the database during the current request cycle. If the sticky option is enabled and a "write" operation has been performed against the database during the current request cycle, any further "read" operations will use the "write" connection. This ensures that any data written during the request cycle can be immediately read back from the database during that same request. It is up to you to decide if this is the desired behavior for your application. 上面那段話是在說,sticky 參數可以立即取得在當下這個請求被寫入的紀錄.當啟用 sticky 時有任何 write 的寫入動作後,所有的 read 操作都會用 write connection. # 設定方式 ```php //database.php 'mysql' => [ 'read' => [ 'host' => [ '192.168.1.1', '196.168.1.2', ], ], 'write' => [ 'host' => [ '196.168.1.3', ], ], // 啟用 sticky 'sticky' => true, 'driver' => 'mysql', 'database' => 'database', 'username' => 'root', 'password' => '', 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', ], ``` # 測試真的是這樣嗎? 下面兩張圖分別是 Read 和 Write 資料可以發現在 name 有不同,read 的是 Jake_read 而 write 的是 Jake 圖1: read ![截圖 2024-03-14 上午11.21.19](https://hackmd.io/_uploads/B1sVa1x0a.png) 圖2: write ![截圖 2024-03-14 上午11.23.07](https://hackmd.io/_uploads/HkSjpkxRa.png) 測試直接撈取第一筆的 user 資料是不是 Jake_read,執行下面的 php code 後的確是因為沒有做任何事情所以撈取到的 user 資料的 name 是 Jake_read ```php dd(User::first()); ``` ![截圖 2024-03-14 上午11.33.38](https://hackmd.io/_uploads/ByRGege0p.png) 測試新增一筆 user 資料的確因為有做 write 的動作(新增user)所以撈取到的 user 資料的 name 是 Jake ```php $user = new User(); $user->email = 'test2@gmail.com'; $user->name = 'Tony'; $user->password = Hash::make(123); $user->save(); dd(User::first()); ``` ![截圖 2024-03-14 上午11.39.08](https://hackmd.io/_uploads/B1Uw-gl0T.png) 下面是新增 user 後目前 user 資料表的資料 圖3. read 資料 ![截圖 2024-03-14 上午11.40.32](https://hackmd.io/_uploads/H1h3-el0p.png) 圖4. write 資料 ![截圖 2024-03-14 上午11.41.01](https://hackmd.io/_uploads/rkuRWxeRp.png) # 結論 經由測試後可以知道,啟用 sticky 參數當寫入資料之後的撈取資料的動作會是用 read 的方式