belongsTo 关联的 withDefault 方法

在 Laravel 5.4 中,新增了一个方法 withDefault,它是结合 belongsTo 一起使用的。所以先要知道,什么是 belongsTo 关联?

什么是 belongsTo 关联?

belongsTo 关联是一对一、一对多关系中,在定义反向关联关系(Inverse Of The Relationship)的 Model 中使用的。比如:

  1. 一对一关系:一个 User 对应一部 Phone,在 Phone Model 中定义的关联就是「一对一关系的反向关联」。
<?php

namespace App;

use App\User;
use Illuminate\Database\Eloquent\Model;

class Phone extends Model
{
    /**
     * Get the user that owns the phone.
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
  1. 一对多关系:一个 User 对应多篇 Article,在 Article Model 中定义的关联就是「一对多关系的反向关联」。
<?php

namespace App\Models;

use App\User;
use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    /**
     * Get the author that owns the article.
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

withDefault 为什么要有?

这个问题问得好:clap:

在实际使用中,可能会出现这样的情况:一个用户删除了,但是与这个用户对应的 Phone 和 Article 记录没有删除。当我们通过 Phone Model 和 Article Model 查询用户时,就有可能返回一个 null 值。

有些时候这个 null 值会引发一些问题,为了解决这个问题, withDefault 应运而生。

/**
 * Get the author that owns the article.
 */
public function user()
{
    return $this->belongsTo(User::class)->withDefault();
}

这种情况下,withDefault 会返回一个 User Model 实例,从而避免了 null 引发的问题。withDefault 方法还支持接收参数, 为生成的实例对象填充数据,参数类型可以是数组或者闭包。

/**
 * Get the author of the article.
 */
public function user()
{
    return $this->belongsTo(User::class)->withDefault([
        'name' => '佚名',
    ]);
}

/**
 * Get the author of the article.
 */
public function user()
{
    return $this->belongsTo(User::class)->withDefault(function ($user) {
        $user->name = '佚名';
    });
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
本帖由系统于 7年前 自动加精
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
讨论数量: 9
滕勇志

今天早上研究代码的时候就看到了 withDefault 当时还疑惑是什么作用,现在知道啦 :smile:

7年前 评论

感谢分享~学习了.

7年前 评论
Complicated

笔记写的真好,这俩天下班了天天来看,,学习了

6年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!