Laravel morphTo 返回 Null

Jos*_*ine 7 php laravel eloquent

我正在使用 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"
  +incrementing: true
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: true
  #attributes: array:13 [
    "StageID" => 12
    "TypeID" => 1
    "OriginID" => 20
    "Description" => "Interested in scanner fi6140"
    "UserID" => 3
    "SolutionValue" => ".00"
    "MarginValue" => ".00"
    "created_at" => "2010-09-16 11:19:00.000"
    "updated_at" => "2015-09-01 12:32:00.000"
    "_migrationID" => "4299"
    "Organization_type" => "App\Account"
    "Organization_id" => 456
    "ID" => 1
  ]
  #original: array:13 [
    "StageID" => 12
    "TypeID" => 1
    "OriginID" => 20
    "Description" => "Interested in scanner fi6140"
    "UserID" => 3
    "SolutionValue" => ".00"
    "MarginValue" => ".00"
    "created_at" => "2010-09-16 11:19:00.000"
    "updated_at" => "2015-09-01 12:32:00.000"
    "_migrationID" => "4299"
    "Organization_type" => "App\Account"
    "Organization_id" => 456
    "ID" => 1
  ]
  #dateFormat: null
  #events: []
  #observables: []
  #relations: array:3 [
    "Organization" => null
    "Projects" => Illuminate\Database\Eloquent\Collection {#3463
      #items: []
    }
    "Tickets" => Illuminate\Database\Eloquent\Collection {#3443
      #items: []
    }
  ]
  #touches: []
  #forceDeleting: false
Run Code Online (Sandbox Code Playgroud)

Jos*_*ine 2

所以,看起来我可能已经发现了我的问题,但我不知道为什么。当车主被询问时

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

看起来 Eloquent 正在寻找organization_type和organization_id(小写),而不是Organization_type和_id。但是,我的迁移使用 $table->morphs('Organization'),因此数据库中的列是用大写字母创建的。当我在数据库中将其更改为小写时,我的结果会返回。但不知道如何改变这种行为,它似乎是从 5.2 升级后引入的

编辑:5.3 中引入了一个更改,蛇形案例 _type 和 _id 这似乎是我的经历的根本原因

https://github.com/laravel/framework/pull/15334