[英]Laravel morphTo Returns 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;
完整的命名空间存储在数据库中,而 _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
在花了两个半天时间探索网上找到的所有解决方案后,我清空了缓存,一切正常......
php artisan cache:clear
所以,看起来我可能已经发现了我的问题,但我不知道为什么。 当所有者被询问时
App\Opportunity::findOrFail(1)->Organization
看起来 Eloquent 正在寻找组织类型和组织 ID(小写)而不是组织类型和 _id。 但是,我的迁移使用 $table->morphs('Organization') ,因此数据库中的列是用大写字母创建的。 当我在数据库中将其更改为小写时,我的结果会返回。 不知道如何改变这种行为,它似乎是从 5.2 升级后引入的
编辑:在 5.3 中引入了一个更改,蛇将 _type 和 _id 放在一起,这似乎是我体验的根本原因
将您的 morphto 更改为此基于文档,以防止混淆 laravel 以检测列类型和列 id
class Image extends Model
{
protected $fillable = [
"link",
"imageable_id",
"imageable_type",
];
public function imagable()
{
return $this->morphTo(__FUNCTION__, 'imageable_type', 'imageable_id');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.