1 回答

TA贡献1784条经验 获得超8个赞
看起来我找到了一个解决方案并修复了一个小错误..至少它看起来像是一个错误,因为我找不到此功能的文档..我通过检查代码找到了它。无论如何,很酷的事情是我们可以用“。”链接关系,因此列设置将如下所示:
$this->crud->addColumn([
'label' => "Rank", // Table column heading
'type' => "select",
'name' => 'promotion_id', // the column that contains the ID of that connected entity;
'entity' => 'promotion.belt', // <- here I'm chaining the model relationships
'attribute' => 'color', // the belt's attribute
'model' => "App\Models\Promotion" // foreign key model
]);
从理论上讲,一切都应该正常工作,但是位于以下位置的方法中有一个小错误vendore\backpack\crud\src\CrudPanel.php:
private function getRelationModelInstances($model, $relationString)
{
$relationArray = explode('.', $relationString);
$firstRelationName = array_first($relationArray);
// this is the line with the bug
//$relation = $model->{$firstRelationName};
// Fix the bug above
if($model instanceof Collection) {
$relation = $model->{$firstRelationName};
} else {
$relation = $model[$firstRelationName];
}
$results = [];
if (! empty($relation)) {
if ($relation instanceof Collection) {
$currentResults = $relation->toArray();
} else {
$currentResults[] = $relation;
}
array_shift($relationArray);
if (! empty($relationArray)) {
foreach ($currentResults as $currentResult) {
$results = array_merge($results, $this->getRelationModelInstances($currentResult, implode('.', $relationArray)));
}
} else {
$results = $currentResults;
}
}
return $results;
}
基本上,这个递归函数在调用自身时将$model参数作为arraynot object..传递,因此当它试图$firstRelationName从$model类似中获取时,这$model->{$firstRelationName}将导致错误。
同时我发现了一个更好的解决方案。为了实现相同的目标,我使用了accessors.
在我的promotion模型中,我有:
/*
|--------------------------------------------------------------------------
| RELATIONS
|--------------------------------------------------------------------------
*/
public function belt()
{
return $this->belongsTo('App\Models\Belt');
}
/*
|--------------------------------------------------------------------------
| ACCESORS
|--------------------------------------------------------------------------
*/
public function getPromotionSummaryAttribute()
{
return $this->belt()->get()[0]->color . ', ' . $this->stripe . ' stripe';
}
因为students我有:
/*
|--------------------------------------------------------------------------
| RELATIONS
|--------------------------------------------------------------------------
*/
public function promotion()
{
return $this->hasMany('App\Models\Promotion');
}
/*
|--------------------------------------------------------------------------
| ACCESORS
|--------------------------------------------------------------------------
*/
public function GetLastPromotionAttribute()
{
return $this->promotion()->get()->last()->promotion_summary;
}
列设置将像这样简单:
$this->crud->addColumn([
'name' => 'last_promotion',
'type' => 'text',
'label' => 'Rank'
]);
我希望这会帮助那里的人:)
- 1 回答
- 0 关注
- 116 浏览
添加回答
举报