當要進行複雜的原生SQL語法查詢才建議你使用 DB Facade,否則一般狀況下還是使用 Eloquent 來進行查詢為好
DB Facade 查詢完得到的會是陣列,而 Eloquent 查詢完得到的則是 Eloquent 物件
如果需要把資料陣列轉換成 Eloquent 是做得到的,透過 Query Builder 的 hydrate(),請看以下範例:
$userData = DB::select('SELECT * FROM users WHERE id > ?', [$userId]);
$userModels = User::hydrate($userData);
任何技術宣稱有實作Active Record,須具備以下三個特性
ORM為Object Relationship Management,即用物件關聯的方式來管理資料庫
不按照命名慣例就要做更多的設定做為代價
生成Model 類別
php artisan make:model Task
生成Model 類別,連帶生成對應的Migration檔案
php artisan make:model Task -m
protected $table = '新表格名稱';
protected $dates = ['sell_at'];
protected $primaryKey = 'user_id';
protected $incrmenting = false;
protected $keyType = 'string';
protected $timestamps = false;
protected $dateFormat = 'U';
const CREATED_AT = 'creation_date';
const UPDATED_AT = 'last_update';
protected $connection = 'connection-name';
//routes/web.php
Route::get('/tasks','SiteController@showTasks');
//App\Http\Controllers\SiteController
public function showTasks(){
return response()->json(Task::get())->setEncodingOptions(JSON_UNESCAPED_UNICODE);
}
or
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up
Syntax | Example | Reference | |
---|---|---|---|
# Header | Header | 基本排版 | |
- Unordered List |
|
||
1. Ordered List |
|
||
- [ ] Todo List |
|
||
> Blockquote | Blockquote |
||
**Bold font** | Bold font | ||
*Italics font* | Italics font | ||
~~Strikethrough~~ | |||
19^th^ | 19th | ||
H~2~O | H2O | ||
++Inserted text++ | Inserted text | ||
==Marked text== | Marked text | ||
[link text](https:// "title") | Link | ||
 | Image | ||
`Code` | Code |
在筆記中貼入程式碼 | |
```javascript var i = 0; ``` |
|
||
:smile: | ![]() |
Emoji list | |
{%youtube youtube_id %} | Externals | ||
$L^aT_eX$ | LaTeX | ||
:::info This is a alert area. ::: |
This is a alert area. |
On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?
Please give us some advice and help us improve HackMD.
Do you want to remove this version name and description?
Syncing