【问题标题】:Mutator and relations突变体和关系
【发布时间】:2016-08-22 00:59:56
【问题描述】:

使用 Laravel 5.2,我在团队模型中设置了一个 mutator:

public function getNameAttribute($value)
{
    if ($this->exists) {
        return !empty($value) ? $value : $this->organization()->first()->name;
    }
    return null;
}

与组织模型的关系:

public function organization()
{
    return $this->belongsToMany('App\Models\Organization')->withTimestamps();
}

$team->name 为空时,我尝试获取$this->organization()->first()->name 但是.. 发生错误:

试图获取非对象的属性

两个小时后,我还没有发现问题

编辑:

Schema::table('organization_team', function (Blueprint $table) {
            $table->foreign('organization_id')
                ->references('id')
                ->on('organizations')
                ->onUpdate('cascade')
                ->onDelete('cascade');

            $table->foreign('team_id')
                ->references('id')
                ->on('teams')
                ->onUpdate('cascade')
                ->onDelete('cascade');
        });

【问题讨论】:

  • 我找到了另一个话题。我认为我有同样的问题。 link 但我不明白他是如何解决问题的。

标签: laravel orm laravel-5 model


【解决方案1】:

$this->organization()->first() 必须在您的应用程序中返回 null。

所以检查你的数据库并添加一些关系数据。

您可以找到这样的组织名称。

$this->organization->first(function ($item) {
    return ! empty($item->name);
})->name;

【讨论】:

  • 当我对此进行 dd() 时,我得到了很好的结果,但没有,仍然是同样的错误。
【解决方案2】:

很简单,就这样吧:

 public function getNameAttribute($value)
    {
        if ($this->exists) {
            return !empty($value) ? $value : $this->organization
                                                   ->first()->name;
        }
        return null;
    }

【讨论】:

  • 您能提供完整的错误信息吗?哪一行抛出该错误?
  • Team.php 中哪一行是 41?
  • 你确定这个团队有与之相关的组织吗?
  • 是的,我已经编辑了我的第一篇文章。但是当我在 $this->organisation->first()->name 上执行 var_dump 时,我得到了我想要的值,但是当我尝试获取 $team->name 时,发生了错误。真的很奇怪。
猜你喜欢
  • 2018-06-20
  • 2018-07-08
  • 2021-10-13
  • 2023-03-18
  • 2020-05-01
  • 2021-05-10
  • 2019-10-19
  • 2018-12-21
  • 2018-01-12
相关资源
最近更新 更多