我正在使用Laravel 5.4并且无法弄清楚为什么无论我做什么,我的morphTo关系总是返回null。关系的反转很好,但是当我尝试检索多态关系的所有者时,它是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;
完整命名空间存储在数据库中,_type和_id实际上在列中具有相应的组织类型和ID(即“App \ Account”和“456”)。所以,我知道数据库记录和返回的Opportunity对象在列中有正确的组织(我可以在数据库中正确看到它),但无论我做什么,如果我尝试检索组织它是null。
这是输出。您会注意到组织属于属性,但关系为null,即使向查询添加 - > 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
答案 0 :(得分:1)
在花了两个半天的时间探索网上找到的所有解决方案之后,我清空了缓存,一切正常...
php artisan cache:clear
答案 1 :(得分:0)
所以,看起来我可能已经发现了我的问题,但我不知道为什么。
查询所有者时App\Opportunity::findOrFail(1)->Organization
看起来Eloquent正在寻找organization_type和organization_id(使用小写)而不是Organization_type和_id。但是,我的迁移使用$ table-> morphs('Organization'),因此数据库中的列是使用大写创建的。当我在数据库中将其更改为小写时,我的结果将被返回。不知道如何改变这种行为,似乎是从5.2
升级后引入的编辑:在5.3中引入了一个变化,蛇案例_type和_id似乎是我经历的根本原因
答案 2 :(得分:0)
基于文档将词法更改为此,以防止laravel混淆以检测列类型和列ID
class Image extends Model
{
protected $fillable = [
"link",
"imageable_id",
"imageable_type",
];
public function imagable()
{
return $this->morphTo(__FUNCTION__, 'imageable_type', 'imageable_id');
}
}