Laravel 9个不经常用的小技巧

栏目: 编程语言 · PHP · 发布时间: 6年前

内容简介:如果你想在更新关联表的同时,更新父表的比如我们有在调用关联时,如果另一个模型不存在,系统会抛出一个致命错误,例如

1. 更新父表的 timestamps

如果你想在更新关联表的同时,更新父表的 timestamps ,你只需要在关联表的 model 中添加 touches 属性。

比如我们有 PostComment 两个关联模型

<?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');
    }
}

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

bladeforeach 中,如果你想获取外层循环的变量

@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::oblyTrashed()->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();

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

淘宝技术这十年

淘宝技术这十年

子柳 / 电子工业出版社 / 2013-5 / 45.00元

《淘宝技术这十年》内容简介:任何网站的发展都不是一蹴而就的。它在发展过程中会遇到各种各样的问题和业务带来的压力。正是这些问题和压力推动着技术的进步和发展,而技术的发展反过来又会促进业务的更大提升。如今淘宝网的流量排名已是全球前15名、国内前3名,其系统服务器也从一台发展到万台以上。 《淘宝技术这十年》从工程师的角度讲述淘宝这个超大规模互联网系统的成长历程,及其所有主动和被动的技术变革的前因后......一起来看看 《淘宝技术这十年》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换