1 回答
TA貢獻1784條經驗 獲得超8個贊
看起來我找到了一個解決方案并修復了一個小錯誤..至少它看起來像是一個錯誤,因為我找不到此功能的文檔..我通過檢查代碼找到了它。無論如何,很酷的事情是我們可以用“?!辨溄雨P系,因此列設置將如下所示:
$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 關注
- 136 瀏覽
添加回答
舉報
