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 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题