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 协议》,转载必须注明作者和本文链接
本帖由系统于 6年前 自动加精
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 9
小滕

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

6年前 评论

感谢分享~学习了.

6年前 评论
Complicated

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

5年前 评论

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