为什么在 Laravel 模型中使用 withDefault() 方法会出现 500 服务器错误?

Why is the usage of withDefault() method in Laravel Models giving 500 Server Error?

在关系方法上使用 withDefault() 会产生服务器错误问题。为什么会这样?有什么原因吗?我相信我在语法上是正确的。

class Product extends Model
{
    protected $table = 'products'; 


    public function category() {
        return $this->hasOne('App\Model\Category', 'id', 'category_id');
    }

    public function images() {
        return $this->hasMany('App\Model\ProductImage', 'product_id', 'id')->withDefault();
    }
}

如果不使用 withDefault() 方法,页面 运行 可以正常显示图像,但使用此方法会触发服务器错误。

belongsTohasOnehasOneThroughmorphOne 关系允许您定义默认模型,如果给定关系为 null,则返回该模型。此模式通常称为空对象模式,可以帮助删除代码中的条件检查。

要使用属性填充默认模型,您可以将数组或闭包传递给 withDefault 方法:

public function images()
{
    return $this->belongsTo('App\Model')->withDefault([
        'name' => 'Test Image',
    ]);
}

根据文档(以及@Hashmat 的回答)

The belongsTo, hasOne, hasOneThrough, and morphOne relationships allow you to define a default model that will be returned if the given relationship is null

这意味着 hasMany 不允许 withDefault。这可能是有道理的,因为当没有相关模型而不是 returning null 时 hasMany 会 return 一个空集合。