Tho*_*ens 1 namespaces polymorphic-associations eloquent laravel-4
我的情况是:日历属于客户或推销员
因为我也有像Event和File这样的类,所以我使用名称空间App\Models作为我所有的模型类.
所以我建立了多态关系:
在Calender.php中
public function user() {
return $this->morphTo();
}
Run Code Online (Sandbox Code Playgroud)
在Customer.php和Salesman.php中
public function calendars() {
return $this->morphMany('App\Models\Calendar', 'user');
}
Run Code Online (Sandbox Code Playgroud)
现在当我这样做
$calendar= Calendar::find(1); //calendar from a salesman
$calendar->user; //error here
...
Run Code Online (Sandbox Code Playgroud)
我收到此错误消息:
Symfony \ Component \ Debug \ Exception \ FatalErrorException
Class 'salesman' not found
Run Code Online (Sandbox Code Playgroud)
我注意到这'salesman'是低壳,也许这是问题?
这就是我从Laravels堆栈跟踪中获得的
打开:/var/www/cloudcube/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php
// foreign key name by using the name of the relationship function, which
// when combined with an "_id" should conventionally match the columns.
if (is_null($foreignKey))
{
$foreignKey = snake_case($relation).'_id';
}
$instance = new $related; //HIGHLIGHTED
Run Code Online (Sandbox Code Playgroud)
我在这一行上遇到类似的错误,当我搞乱名称空间时,所以我猜它与此有关.有什么办法可以告诉morphTo()方法使用正确的命名空间吗?
或者它是导致此问题的其他原因?
也找到了这个解决方案,但似乎无法让它工作: 与命名空间的多态Eloquent关系
我找到了一个适合我的解决方案.
我总是用正确的命名空间定义关系,例如在Calendar中:
public function events() {
return $this->hasMany('App\Models\Event');
}
我的问题包括两个并发症:
$calendar->user()morphTo(...)由于我的模型在命名空间中,并且morphTo(...)无法提供此命名空间,因此该函数无法正常工作.
$salesman->calenders()->get()返回和清空列表,虽然我在数据库中的关系存在.我发现这是因为与查询绑定.
解决方案1:morphTo(...)在日历中编写自定义函数以覆盖Laravel之一.我用Laravels的来源morphTo(...)作为基础.这个函数的最后声明是return $this->belongsTo($class, $id);
有$class一定的命名空间中的类名.我使用基本的字符串操作来关闭它.
2的解决方案:morphMany(...)在Salesman中编写自定义函数,并让它返回MyMorphMany(...)类似于描述的名称空间的多态Eloquent关系.
这里的问题$query是传递给MyMorphMany构造函数的具有错误的(命名空间)绑定.它会寻找where user_type = "App\\Models\\Salesman".
为了解决这个问题,我使用了一个自定义getResults()函数MyMorphMany来覆盖默认的Laravels实现,在那里我更改了绑定以使用正确的,未命名空间的低级别的类名.然后我在类getResults()的get()函数中调用了这个函数MyMorphMany.
我使用$query->getBindings()并$query->setBindings()纠正了绑定.
希望这可以节省其他人几天的工作,就像它会救了我一样:)
| 归档时间: |
|
| 查看次数: |
3221 次 |
| 最近记录: |