国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > PHP > 正文

Laravel中9個不經常用的小技巧匯總

2024-05-05 00:08:32
字體:
來源:轉載
供稿:網友

前言

眾所周知Laravel是一套簡潔、優雅的PHP Web開發框架(PHP Web Framework)。下面這篇文章主要給大家總結了一些Laravel不經常用的小技巧,下面話不多說了,來一起看看詳細的介紹吧

1. 更新父表的timestamps

如果你想在更新關聯表的同時,更新父表的timestamps,你只需要在關聯表的model中添加touches屬性。
比如我們有Post和Comment兩個關聯模型

<?phpnamespace App;use Illuminate/Database/Eloquent/Model;class Comment extends Model{ /**  * 要更新的所有關聯表  *  * @var array  */ protected $touches = ['post']; /**  * Get the post that the comment belongs to.  */ public function post() {  return $this->belongsTo('App/Post'); }}

2. 懶加載指定字段

$posts = App/Post::with('comment:id,name')->get();

3. 跳轉指定控制器并附帶參數

return redirect()->action('SomeController@method', ['param' => $value]);

4. 關聯時使用withDefault()

在調用關聯時,如果另一個模型不存在,系統會拋出一個致命錯誤,例如 $comment->post->title,那么我們就需要使用withDefault()

...public function post(){ return $this->belongsTo(App/Post::class)->withDefault();}

5. 兩層循環中使用$loop

在blade的foreach中,如果你想獲取外層循環的變量

@foreach ($users as $user)   @foreach ($user->posts as $post)    @if ($loop->parent->first)      This is first iteration of the parent loop.    @endif   @endforeach @endforeach

6. 瀏覽郵件而不發送

如果你使用的是mailables來發送郵件,你可以只展示而不發送郵件

Route::get('/mailable', function () { $invoice = App/Invoice::find(1); return new App/Mail/InvoicePaid($invoice);});

7. 通過關聯查詢記錄

在hasMany關聯關系中,你可以查詢出關聯記錄必須大于5的記錄

$posts = Post::has('comment', '>', 5)->get();

8. 軟刪除

查看包含軟刪除的記錄

$posts = Post::withTrashed()->get();

查看僅被軟刪除的記錄

$posts = Post::onlyTrashed()->get();

恢復軟刪除的模型

Post::withTrashed()->restore();

9. Eloquent時間方法

$posts = Post::whereDate('created_at', '2018-01-31')->get(); $posts = Post::whereMonth('created_at', '12')->get(); $posts = Post::whereDay('created_at', '31')->get(); $posts = Post::whereYear('created_at', date('Y'))->get(); $posts = Post::whereTime('created_at', '=', '14:13:58')->get();

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對VeVb武林網的支持。


注:相關教程知識閱讀請移步到PHP教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 亚东县| 且末县| 新昌县| 汝阳县| 怀来县| 闻喜县| 武安市| 九江县| 侯马市| 阿图什市| 阳高县| 金沙县| 平乡县| 璧山县| 星座| 沧州市| 枣强县| 达尔| 梅河口市| 通城县| 原平市| 金昌市| 惠来县| 莱芜市| 福清市| 乐业县| 十堰市| 浮山县| 仙游县| 石首市| 揭东县| 固始县| 赤水市| 股票| 富裕县| 渭源县| 卢氏县| 开原市| 和田县| 关岭| 浦江县|