belongsTo 关联的 withDefault 方法
在 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
为什么要有?
这个问题问得好: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年前 自动加精
今天早上研究代码的时候就看到了
withDefault
当时还疑惑是什么作用,现在知道啦 :smile:@轻色年华 哈哈,感谢鼓励!
感谢分享~学习了.
@無限之秋 :simple_smile:
get!
这个好,用起来
学习了
笔记写的真好,这俩天下班了天天来看,,学习了
@Complicated 谢谢你的鼓励 加油!