小编Jos*_*ine的帖子

Laravel morphTo 返回 Null

我正在使用 Laravel 5.4 并且无法弄清楚为什么无论我做什么我的 morphTo 关系总是返回 null。关系的逆很好,但是当我尝试检索多态关系的所有者时,它为空。

class Opportunity extends Model {

    public function Organization() {
        return $this->morphTo('Organization');
    }

}

class Account extends model {

    public function Opportunities() {
            return $this->morphMany('App\Opportunity', 'Organization');
        }
}

class Department extends model {

    public function Opportunities() {
            return $this->morphMany('App\Opportunity', 'Organization');
        }
}

$org = App\Opportunity::findOrFail(1)->Organization;
Run Code Online (Sandbox Code Playgroud)

完整的命名空间存储在数据库中,而 _type 和 _id 实际上在列中具有适当的组织类型和 id(即“App\Account”和“456”)。所以,我知道数据库记录和返回的 Opportunity 对象在列中具有正确的组织(我可以在数据库中正确地看到它),但无论我做什么,如果我尝试检索组织,它都是空的。

这是输出。您会注意到组织在属性中,但关系为空,即使将 ->with('Organization') 添加到查询中,我也无法让它返回。它甚至似乎没有执行查询来获取所有者

#primaryKey: "ID"
  +timestamps: true
  #guarded: []
  #hidden: []
  #visible: []
  #with: []
  #dissociateRelations: []
  #connection: null
  #keyType: "int" …
Run Code Online (Sandbox Code Playgroud)

php laravel eloquent

7
推荐指数
1
解决办法
2519
查看次数

标签 统计

eloquent ×1

laravel ×1

php ×1