当前位置: 首页 > 后端技术 > PHP

Laravel9不常用小技巧

时间:2023-03-29 23:07:15 PHP

1.更新父表的时间戳如果想在更新关联表的同时更新父表的时间戳,只需要在关联表的model中添加touches属性即可。例如,我们有两个关联模型Post和CommentbelongsTo('App\Post');}}2。延迟加载指定字段$posts=App\Post::with('comment:id,name')->get();3.跳转到带参数的指定控制器returnredirect()->action('SomeController@method',['param'=>$value]);4.调用关联时使用withDefault()。如果另一个模型不存在,系统会抛出致命错误,比如$comment->post->title,这时我们需要使用withDefault()...publicfunctionpost(){return$this->belongsTo(App\Post::class)->withDefault();}5.在两层循环的blade的foreach中使用$loop,如果你想获取外层循环的变量@foreach($usersas$user)@foreach($user->postsas$post)@if($loop->parent->first)这是冷杉父循环的第st次迭代。@endif@endforeach@endforeach6。Browsemailwithoutsending如果你使用mailables发送邮件,你可以只显示而不发送邮件Route::get('/mailable',function(){$invoice=App\Invoice::find(1);returnnewApp\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();