1. 更新父表的timestamps
www.archcn.net
如果你想在更新關聯表的同時,更新父表的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
時間方法
<span type="button" created_at',="" '2018-01-31')-="" style="box-sizing: border-box;">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();" title="">
$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();