Значения списка рюкзаков Laravel с отношением полей

Я пытаюсь перечислить значения из таблицы, которая содержит отношения, созданные в модели, но вместо имени, связанного с этим идентификатором, отображается идентификатор:

Нравится здесь

District.php и миграция:

<?php

    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Model;
    use Backpack\CRUD\CrudTrait;
    
    class District extends Model
    {
        use CrudTrait;
    
         /*
        |--------------------------------------------------------------------------
        | GLOBAL VARIABLES
        |--------------------------------------------------------------------------
        */
    
        protected $table = 'districts';
        protected $primaryKey = 'id';
        // public $timestamps = false;
        // protected $guarded = ['id'];
        protected $fillable = ['name'];
        // protected $hidden = [];
        // protected $dates = [];
    
        /*
        |--------------------------------------------------------------------------
        | FUNCTIONS
        |--------------------------------------------------------------------------
        */
    
        /*
        |--------------------------------------------------------------------------
        | RELATIONS
        |--------------------------------------------------------------------------
        */
        public function county()
        {
            return $this->hasMany('App\Models\County');
        }

Миграция:

<?php   
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Database\Migrations\Migration;
    
    class CreateDistrictsTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('districts', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name')->unique();
                $table->timestamps();
            });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::drop('districts');
        }
    }`

County.php

<?php
    
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Model;
    use Backpack\CRUD\CrudTrait;
    
    class County extends Model
    {
        use CrudTrait;
    
         /*
        |--------------------------------------------------------------------------
        | GLOBAL VARIABLES
        |--------------------------------------------------------------------------
        */
    
        protected $table = 'counties';
        protected $primaryKey = 'id';
        // public $timestamps = false;
        // protected $guarded = ['id'];
        protected $fillable = ['name', 'DistrictID'];
        // protected $hidden = [];
        // protected $dates = [];
        //$this->table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    
        /*
        |--------------------------------------------------------------------------
        | FUNCTIONS
        |--------------------------------------------------------------------------
        */
    
        /*
        |--------------------------------------------------------------------------
        | RELATIONS
        |--------------------------------------------------------------------------
        */
        public function district() {
            return $this->belongsTo('App\Models\District');
        }
    }

Миграция:

<?php
    
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Database\Migrations\Migration;
    
    class CreateDistrictsTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('districts', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name')->unique();
                $table->timestamps();
            });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::drop('districts');
        }
    }

CountyCrudController.php

<?php
    
    namespace App\Http\Controllers\Admin;
    
    use Backpack\CRUD\app\Http\Controllers\CrudController;
    
    // VALIDATION: change the requests to match your own file names if you need form validation
    use App\Http\Requests\CountyRequest as StoreRequest;
    use App\Http\Requests\CountyRequest as UpdateRequest;
    
    use App\Models\District as District;
    
    class CountyCrudController extends CrudController
    {
    
        public function setUp()
        {
    
            /*
            |--------------------------------------------------------------------------
            | BASIC CRUD INFORMATION
            |--------------------------------------------------------------------------
            */
            $this->crud->setModel('App\Models\County');
            $this->crud->setRoute(config('backpack.base.route_prefix') . '/county');
            $this->crud->setEntityNameStrings('county', 'counties');
    
            /*
            |--------------------------------------------------------------------------
            | BASIC CRUD INFORMATION
            |--------------------------------------------------------------------------
            */
    
            //$this->crud->setFromDb();
    
            // ------ CRUD FIELDS
            // $this->crud->addField($options, 'update/create/both');
            // $this->crud->addFields($array_of_arrays, 'update/create/both');
            // $this->crud->removeField('name', 'update/create/both');
            // $this->crud->removeFields($array_of_names, 'update/create/both');
    
            $this->crud->addColumn([
                'name' => 'name', // The db column name
                'label' => "County", // Table column heading
                'type' => 'text'
            ]);
    
            $this->crud->addColumn([
                'label' => "District", // Table column heading
                'type' => "text",
                'name' => 'DistrictID', // the column that contains the ID of that connected entity;
                'entity' => 'district', // the method that defines the relationship in your Model
                'attribute' => "name", // foreign key attribute that is shown to user
                'model' => 'App\Models\District' // foreign key model
            ]);
    
            $this->crud->setColumnDetails('DistrictID', ['attribute' => 'name']);
    
            $this->crud->addField([
                'name' => 'name', // The db column name
                'label' => "County" // Table column heading
            ]);
    
            $this->crud->addField([
                'label' => 'District', // Label for HTML form field
                'type'  => 'select2',  // HTML element which displaying transactions
                'name'  => 'DistrictID', // Table column which is FK for Customer table
                'entity'=> 'district', // Function (method) in Customer model which return transactions
                'attribute' => 'name', // Column which user see in select box
                'model' => 'App\Models\District' // Model which contain FK
            ]);

person Duarte Andrade    schedule 05.06.2017    source источник


Ответы (1)


Что вам нужно сделать, это изменить этот код:

$this->crud->addColumn([
        'label' => "District", // Table column heading
        'type' => "text",
        'name' => 'DistrictID', // the column that contains the ID of that connected entity;
        'entity' => 'district', // the method that defines the relationship in your Model
        'attribute' => "name", // foreign key attribute that is shown to user
        'model' => 'App\Models\District' // foreign key model
    ]);

$this->crud->setColumnDetails('DistrictID', ['attribute' => 'name']);

to :

$this->crud->setColumnDetails([
        'label' => "District", // Table column heading
        'type' => "select",
        'name' => 'DistrictID', // the column that contains the ID of that connected entity;
        'entity' => 'district', // the method that defines the relationship in your Model
        'attribute' => "name", // foreign key attribute that is shown to user
        'model' => 'App\Models\District' // foreign key model
    ]);

Примечание. $this->crud->addColumn и $this->crud->setColumnDetails заменены только на $this->crud->setColumnDetails.

person rylxes    schedule 15.06.2017