timestamps
若是你想在更新關聯表的同時,更新父表的timestamps
,你只須要在關聯表的model
中添加touches
屬性。
好比咱們有Post
和Comment
兩個關聯模型php
<?php namespace 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'); } }
$posts = App\Post::with('comment:id,name')->get();
return redirect()->action('SomeController@method', ['param' => $value]);
withDefault()
在調用關聯時,若是另外一個模型不存在,系統會拋出一個致命錯誤,例如 $comment->post->title
,那麼咱們就須要使用withDefault()
oop
... public function post() { return $this->belongsTo(App\Post::class)->withDefault(); }
$loop
在blade
的foreach
中,若是你想獲取外層循環的變量post
@foreach ($users as $user) @foreach ($user->posts as $post) @if ($loop->parent->first) This is first iteration of the parent loop. @endif @endforeach @endforeach
若是你使用的是mailables
來發送郵件,你能夠只展現而不發送郵件this
Route::get('/mailable', function () { $invoice = App\Invoice::find(1); return new App\Mail\InvoicePaid($invoice); });
在hasMany
關聯關係中,你能夠查詢出關聯記錄必須大於5的記錄spa
$posts = Post::has('comment', '>', 5)->get();
查看包含軟刪除的記錄rest
$posts = Post::withTrashed()->get();
查看僅被軟刪除的記錄code
$posts = Post::onlyTrashed()->get();
恢復軟刪除的模型get
Post::withTrashed()->restore();
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();