首页 > 解决方案 > 如何返回对象而不是数组中的对象

问题描述

由于 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(),它会返回一个包含所需对象的数组。我只想根据关系检索对象。任何帮助表示赞赏。

标签: laraveleloquenteloquent-relationship

解决方案


试试这个:

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

推荐阅读