laravel-admin 關於多列一對多的展現問題

關於多列一對多的展現問題

表 china_area

id parent_id code name
1 0 100000 中華人民共和國

模型定義

class ChinaArea extends Model 
{
    protected $table = 'china_area'; // 定義模型對應的數據庫表名
    public $timestamps = false; // 關閉自動添加建立時間和更新時間
    
    public parent()
    {
        // 參數列表爲:模型(ChinaArea::class),外鍵列名(parent_id),本地鍵列名(id)
        return $this->belongsTo(ChinaArea::class, 'parent_id');
    }
    ...
}

表 demo_addresses

id name mobile province_id city_id district_id address
1 xiaoming 1337033xxxx 370000 370100 370102 中鐵財智中心

模型定義

class Address extends Model
{
    protected $table = 'demo_addresses'; // 定義模型對應的數據庫表名
    // 省的關聯
    public function province()
    {    
        return $this->belongsTo(ChinaArea::class, 'province_id', 'code');
    }
    // 市的關聯
    public function city()
    {
        return $this->belongsTo(ChinaArea::class, 'city_id', 'code');
    }
    // 區的關聯
    public function district()
    {
        return $this->belongsTo(ChinaArea::class, 'district_id', 'code');
    }
}

數據表格 grid 的列展現

// 本表的列展現
$grid->column('name', __('Contact Name'));
// 關聯數據的展現
$grid->column('province.name', __('Province'));
// 合併多列的展現
$grid->column('Area',__('Area'))->display(function (){
    return $this->province->name.'-'.$this->city->name.'-'.$this->district->name;
});

詳情 detail 的數據展現

// 默認模型查詢
// $show = new Show(Address::findOrFail($id)); 
// 展現關聯列數據的時候,必須從新定義模型查詢
$address = Address::with('province')->with('city')->with('district')->findOrFail($id);
$show = new Show($address);
// 本表數據的展現
$show->field('name', __('Contact Name'));
$show->mobile(__('Contact Phone'));
// 展現關聯列數據的時候,必須從新定義模型查詢
$show->field('anyName', __('Area'))->as(function (){
        return $this->getRelation('province')->name.'-'.$this->getRelation('city')->name.'-'.$this->getRelation('district')->name;
});

相關文章
相關標籤/搜索