界面
代码
<?php
namespace App\Admin\Controllers\Demo;
use App\Models\Demo\Painter;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Widgets\Tab;
class PainterController extends Controller
{
use ModelForm;
...
protected function grid()
{
return Admin::grid(Painter::class, function (Grid $grid) {
$grid->id('ID')->sortable();
$grid->username()->editable();
$grid->paintings()->pluck('title')->map(function ($title) {
return "<strong><i>《$title》</i></strong>";
})->implode('<br />');
$grid->created_at();
$grid->updated_at();
});
}
protected function form()
{
return Admin::form(Painter::class, function (Form $form) {
$form->display('id', 'ID');
$form->text('username')->rules('required');
$form->textarea('bio')->rules('required');
$form->hasMany('paintings', function (Form\NestedForm $form) {
$form->text('title');
$form->textarea('body');
$form->datetime('completed_at');
});
$form->display('created_at', 'Created At');
$form->display('updated_at', 'Updated At');
});
}
...
}
模型
app/Models/Demo/Painter.php
<?php
namespace App\Models\Demo;
use Illuminate\Database\Eloquent\Model;
class Painter extends Model
{
protected $table = 'demo_painters';
public function paintings()
{
return $this->hasMany(Painting::class, 'painter_id');
}
}
app/Models/Demo/Painting.php
<?php
namespace App\Models\Demo;
use Illuminate\Database\Eloquent\Model;
class Painting extends Model
{
protected $table = 'demo_paintings';
protected $fillable = ['title', 'body', 'completed_at'];
public function painter()
{
return $this->belongsTo(Painter::class, 'painter_id');
}
}
表结构
CREATE TABLE `demo_painters` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`bio` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `demo_paintings` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`painter_id` int(10) unsigned NOT NULL,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`body` text COLLATE utf8_unicode_ci NOT NULL,
`completed_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`),
KEY painter_id (`painter_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-END-