【问题标题】:using withDefault() on belongsTo results in error在 belongsTo 上使用 withDefault() 会导致错误
【发布时间】:2017-12-16 05:09:52
【问题描述】:
public function featuredimage()
{
    return $this->belongsTo(Image::class, 'featured_image_id')->withDefault();
}

这给了我:调用模型 [App\Models\Core\Blog\Post] 上的未定义关系 [featuredimage]。

任何想法为什么?

它应该根据文档工作:

https://laravel.com/docs/5.4/eloquent-relationships#updating-belongs-to-relationships

默认模型

belongsTo 关系允许您定义一个默认模型 如果给定的关系为空,将返回。这个图案是 通常被称为空对象模式,可以帮助删除 在您的代码中进行条件检查。在以下示例中,用户 如果没有附加用户,关系将返回一个空的 App\User 模型 发帖:

public function user()
{
    return $this->belongsTo('App\User')->withDefault();
}

我的 laravel 版本:5.4.27

我有两张桌子:

帖子表和图片表

在 post 表中我这样做:

$table->biginteger('featured_image_id')->nullable()->unsigned();

$table->foreign('featured_image_id')->references('id')->on('images')->onUpdate('cascade')->onDelete('cascade');

【问题讨论】:

  • 你能分享你的数据库设计吗?
  • 更新了我的问题
  • 还有你的图片表?
  • 试试这个return $this->belongsTo(Image::class, 'featured_image_id', 'id')->withDefault();
  • 您将image.php 文件放在哪里?

标签: laravel eloquent


【解决方案1】:

我有同样的问题。您需要升级到最新的 laravel 版本,因为 withDefault 方法从 5.4.28 开始可用。

要更新,只需运行:

composer update

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    • 2018-08-08
    • 2017-12-22
    • 2012-02-12
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    相关资源
    最近更新 更多