【问题标题】:Laravel getRelations() returns blankLaravel getRelations() 返回空白
【发布时间】:2015-08-12 01:33:49
【问题描述】:

我正在尝试查询与访问器一起使用的关系 getNameAttribute 这是我的代码

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Conference extends Model{

    public function getNameAttribute() {
        return $this->getRelation('event')->name;
    }

    public function event() {
        return $this->belongsTo('App\Event');
    }

    public function speakers() {
        return $this->hasMany('App\Speaker');
    }
}

但它什么都没有返回。我做错了什么吗? 谢谢!

【问题讨论】:

    标签: php laravel foreign-keys


    【解决方案1】:

    getRelationValue 是引入相关模型的好方法,您将在该模型上执行聚合函数。计数可以使用 withCount,但对于求和和平均值,getRelationValue 在预加载时比直接调用相关模型效果更好。

    【讨论】:

      【解决方案2】:

      您想改用getRelationValue

      public function getNameAttribute() {
          return $this->getRelationValue('event')->name;
      }
      

      如果关系尚未加载,此方法将加载它。

      【讨论】:

        【解决方案3】:

        在您请求关系event 时,此关系尚未加载,这就是您获得空值的原因。如果您想访问 event 关系,只需执行此操作 $this-&gt;event 它将加载它,因此您可以访问它的属性:

        public function getNameAttribute() {
            return $this->event->name;
        }
        

        getRelation 方法会返回一个关系,如果它已经加载到模型中,则不会触发加载。

        【讨论】:

        • 哇,这很简单,它怎么能访问活动?通过雄辩的 ORM?
        • @Notflip 是的,它正在触发 Eloquent 的魔法__get 方法。您可以查看documentation,它有很多很酷的技巧和窍门。
        猜你喜欢
        • 2021-08-12
        • 1970-01-01
        • 1970-01-01
        • 2021-09-14
        • 2018-03-28
        • 2018-12-23
        • 2021-09-15
        • 2021-01-09
        • 2017-11-20
        相关资源
        最近更新 更多