【问题标题】:Load Model relations from a Observer method从观察者方法加载模型关系
【发布时间】:2021-02-16 14:29:24
【问题描述】:

如何从观察者中的模型加载关系?
当我尝试使用$inport->load('items') 在created 方法中加载关系时,它返回一个空数组。
这是我的Inport 模型中定义的关系:

public function items()
{
    return $this->hasMany(InportItem::class);
}

观察者法

public function created(Inport $inport)
{
    dd($inport->load('items'));
}

Inport表

id
name

inport_items表

id
inport_id
number

【问题讨论】:

  • 你的 laravel 版本是什么?
  • @user15070659 我的版本是8.27,我会更新标题。
  • 你能分享更多信息吗?例如,您的主 ID 和外国 ID。这很重要。
  • @r89human inport_items 表使用来自inport 表的id 的外键inport_id 连接

标签: laravel eloquent laravel-8


【解决方案1】:

你需要尝试

dd( $inport->items );

你的 items() 方法应该是这样的。

public function items()
{
    return $this->hasMany(InportItem::class, 'inport_id', 'id'); // where inport_id is your foreign key and id is your primary key in inport_items table
}

【讨论】:

  • 我之所以尝试Load 关系是因为观察者看不到模型的关系。 dd( $inport->items ) 返回一个空数组。是的,我的数据库中有数据。是的,dd( $inport->items ) 在observer 类之外工作并返回所需的数据。
【解决方案2】:

观察者看不到这个关系,因为它还没有被创建。

hasMany 关系意味着InportItem 类存储了你的Inport 模型的id,它只能存储你的Inport 模型的id在创建之后。

您的选择:

  • 尝试在您的观察者上使用afterCommit property(我不确定这是否可行)
  • 在InportItem 模型上使用created 事件的观察者,而不是Inport 模型(您可能希望在InportItem 上添加belongsTo 将其链接到Inport)李>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-12
    • 2022-01-24
    • 1970-01-01
    • 2021-02-13
    • 2016-02-20
    相关资源
    最近更新 更多