doujia7094 2019-04-24 15:58
浏览 95
已采纳

Eloquent关系集合不是由属性访问器返回,但如果我使用relation() - > get();

I'm having an issue with eloquent whereby when I call $unit->assets I am receiving an empty collection. But if I call $unit->assets()->get() - I receive a collection with the correct results.

According to the documentation my relations are defined correctly, which also seems apparent given that I get correct results when calling get() on the relationship object.

class Unit extends Model
{
    protected $table = 'organisation_units';

    public function assets()
    {
        return $this->hasMany(MediaElement::class, 'owner_id');
    }
}

class MediaElement extends Model
{
    protected $table = 'template_elements';

    public function owner()
    {
        return $this->belongsTo(Unit::class, 'owner_id');
    }
}

Table structure is

organisation_units

id | name

template_elements

id | owner_id | name | filename

  • 写回答

1条回答 默认 最新

  • duanchuiwen6694 2019-04-24 16:06
    关注

    Turns out the issue was the fact that I use "assets" as the relation method name. "assets" must be a reserved or already used keyword within models or something. Will update the post when I find out exactly why.

    Also had the same issue with the method names "colors" and "templates".

    The real issue here, was that I was storing my organisation unit in the session and when retrieving that from the session, the relations were already loaded.

    Calling $model->fresh() before saving to the session sorted out the issue.

    Thanks to those who attempted to help.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)