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();