【问题标题】:how to return object instead of object in array如何返回对象而不是数组中的对象
【发布时间】:2018-12-25 06:02:56
【问题描述】:

由于 hasMany 的关系,我正在尝试返回来自集合数组的对象的响应。

我已经尝试过退货$block->where('date','=',$today)->first();

错误说:调用未定义的方法 App\BlockDate::addEagerConstraints()

public function block_dates() 
{
    return $this->hasMany(BlockDate::class);
}

public function schedule_block() 
{
    $today = Carbon::today()->toDateString();
    $block = $this->block_dates();

    return $block->where('date','=',$today)->first();
}

schedule_block() 应该返回BlockDate 的对象。如果我删除first(),它会返回一个包含所需对象的数组。我只想根据关系检索对象。任何帮助表示赞赏。

【问题讨论】:

  • 你怎么称呼->schedule_block()
  • 最后添加 ->toArray() 可能有助于将对象转换为数组
  • @Ijas schedule_block() 是从带有 with() Joshi 的控制器调用的 - 我试图获取对象,而不是使其成为数组

标签: laravel eloquent eloquent-relationship


【解决方案1】:

试试这个:

public function schedule_block() {
    $today = Carbon::today()->toDateString();
    return $this->hasOne(BlockDate::class)->where('date','=',$today);
}

【讨论】:

  • @NewProgrammer,它有效吗?或者您收到任何错误?
  • 是的,它正在工作,但我很困惑。关系 hasOne 没有指向具有 schedule_id 的 BlockDates 的第一个条目,我认为它会。它是如何工作的?
  • block_dates() 使用与BlockDate 类的hasMany 关系,这将返回array(),但由于您只想获取一条记录作为对象,所以我使用hasOneBlockDate 的关系class ,它将返回 Object.
  • 从技术上讲,Schedule 类与 BlockDate 类有很多关系,是的,这就是它返回数组的原因。我只是对 where() 如何为 hasOne 工作感到困惑。谢谢你的澄清。
  • where 也可以与 hasMany 一起使用,但它会将结果作为数组而不是对象返回
猜你喜欢
  • 2020-06-29
  • 2020-05-06
  • 1970-01-01
  • 2020-04-11
  • 2018-07-05
  • 1970-01-01
  • 2019-10-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多