我有 Region 作为服务器的查找表。 在表上列出已保存的条目没有问题。 但是,当我编辑条目时,该字段未预先选择保存的值。我该如何设置?
-- Table --
Schema::create('servers', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->integer('region_id')->unsigned();
$table->timestamps();
Schema::table('servers', function(Blueprint $table) {
$table->foreign('region_id')->references('id')->on('lookup_regions')->onDelete('restrict')->onUpdate('restrict');
});
Schema::create('lookup_regions', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->timestamps();
});
-- Model --
class Server extends Model
{
public function region()
{
return $this->hasOne('App\Models\Region', 'id', 'region_id');
}
}
class Region extends Model
{
public function server()
{
return $this->belongsTo('App\Models\Server', 'id', 'region_id');
}
}
-- Controller --
class ServerCrudController extends CrudController
{
$this->crud->addColumn([
'label' => 'Region',
'type' => 'select',
'name' => 'region_id',
'entity' => 'region',
'attribute' => 'name',
'model' => 'App\Models\Region'
]);
$this->crud->addField([
'label' => 'Region',
'type' => 'select',
'name' => 'region_id',
'entity' => 'region',
'attribute' => 'name',
'model' => 'App\Models\Region',
]);
}
答案 0 :(得分:1)
在模型中放置正确的hasOne和belongsTo解决了该问题
-- Model --
-- Server.php --
public function provider()
{
return $this->belongsTo('App\Models\Provider', 'provider_id', 'id');
}
-- Region.php --
public function proxy()
{
return $this->hasOne('App\Models\Proxy', 'id', 'region_id');
}
-- Controller --
-- ServerCrudController.php --
$this->crud->addField([
'label' => 'Region',
'type' => 'select',
'name' => 'region_id',
'entity' => 'region',
'attribute' => 'name',
'model' => 'App\Models\Region',
]);
答案 1 :(得分:0)
尝试使用默认属性,例如
$this->crud->addColumn([
'label' => 'Region',
'type' => 'select_from_array',
'name' => 'region_id',
'entity' => 'region',
'attribute' => 'name',
'model' => 'App\Models\Region'
'options' => [
'val1' => "value1",
'val2' => "value2"
],
'default' => 'val1',
]);
希望这会有所帮助。