【问题标题】:Why is the usage of withDefault() method in Laravel Models giving 500 Server Error?为什么在 Laravel 模型中使用 withDefault() 方法会产生 500 服务器错误?
【发布时间】:2020-04-05 17:34:15
【问题描述】:

在关系方法中使用 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() 方法,页面可以正常运行并显示图像,但使用此方法会触发服务器错误。

【问题讨论】:

  • 一个 500 会伴随一个错误。检查您的 error_logs 或更改设置以显示所有错误。
  • 那么,错误说明了什么?
  • 代码图像不是实际代码。请使用您正在使用的实际代码编辑您的问题。使人们更容易复制/粘贴以尝试复制问题的东西
  • [2019-12-12 11:05:25] local.ERROR:调用模型 [App\Model\Product] 上的未定义关系 [images]。 {"exception":"[object] (Illuminate\\Database\\Eloquent\\RelationNotFoundException(code: 0): 调用模型 [App\\Model\\Product] 上未定义的关系 [images]。在 C:\\ xampp\\htdocs\\theliquorshop\\tls_api\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Eloquent\\RelationNotFoundException.php:34)
  • 关系在没有 withDefaults() 方法的情况下工作正常

标签: php laravel eloquent laravel-6


【解决方案1】:

belongsTohasOnehasOneThroughmorphOne 关系允许您定义在给定关系为空时将返回的默认模型。这种模式通常被称为空对象模式,可以帮助您删除代码中的条件检查。

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

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

【讨论】:

  • 我明白了这一点,但这件事不起作用。在 images 方法的 hasMany 关系上使用默认方法仍然给出错误。
  • 您要传递的默认属性值是什么?您收到的错误信息是什么?
  • [2019-12-12 11:05:25] local.ERROR:调用模型 [App\Model\Product] 上的未定义关系 [images]。 {"exception":"[object] (Illuminate\\Database\\Eloquent\\RelationNotFoundException(code: 0): 调用模型 [App\\Model\\Product] 上未定义的关系 [images]。在 C:\\ xampp\\htdocs\\theliquorshop\\tls_api\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Eloquent\\RelationNotFoundException.php:34)
  • 关系工作正常,但没有 withDefault() 方法
【解决方案2】:

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

belongsTohasOnehasOneThroughmorphOne 关系允许您定义一个默认模型,如果给定关系为空,将返回该模型

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-07
    • 2013-09-20
    • 1970-01-01
    相关资源
    最近更新 更多