🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
在 Laravel 5.4 中,新增了一个方法 withDefault,它是结合 belongsTo 一起使用的。所以先要知道,什么是 belongsTo 关联? 什么是 belongsTo 关联 belongsTo 关联是一对一、一对多关系中,在定义反向关联关系(Inverse Of The Relationship)的 Model 中使用的。比如: 一对一关系:一个 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); } } ~~~ 一对多关系:一个 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 为什么要有 这个问题问得好 在实际使用中,可能会出现这样的情况:一个用户删除了,但是与这个用户对应的 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 引发的问题。当然,你还可以为这个实例填充数据:使用数组或者闭包形式的参数。 ~~~ /** * 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 = '佚名'; }); } ~~~