Laravel-背包选择取决于另一个选择

时间:2020-06-19 10:58:48

标签: php json ajax laravel backpack-for-laravel

我最近在我的Laravel项目中安装了Laravel Backpack管理员。目前,我正在努力。但是我需要帮助。所以...

我想要的东西:

我想有两个选择,第一个是Category,第二个是Article。因此,Article选择必须取决于Category选择。还有Article belongsTo Category

类别文章

Category 1 = [ Article 1, Article 2, Article 3 ]
Category 2 = [ Article 4, Article 5 ]

这只是显示哪个文章属于类别。因此,例如,当我在Category 1上单击category时,在article上选择的内容应该只显示Article 1, Article 2 and Article 3

我做什么

我遵循了背包文档上有关linkAdd a select2 field that depends on another field的说明。所以我首先要做的:

我创建了两个表,Category表和Article表。他们的模型:

class Category extends Model
{
    use CrudTrait;

    /*
    |--------------------------------------------------------------------------
    | GLOBAL VARIABLES
    |--------------------------------------------------------------------------
    */

    protected $table = 'categories';
    protected $primaryKey = 'id';
    // public $timestamps = false;
    // protected $guarded = ['id'];
    protected $fillable = ['title'];
    // protected $hidden = [];
    // protected $dates = [];

    /*
    |--------------------------------------------------------------------------
    | FUNCTIONS
    |--------------------------------------------------------------------------
    */

    public function articles(){
        return $this->hasMany('App\Models\Article');
    }
}

这是一个Category模型,这是Article模型:

class Article extends Model
{
    use CrudTrait;

    /*
    |--------------------------------------------------------------------------
    | GLOBAL VARIABLES
    |--------------------------------------------------------------------------
    */

    protected $table = 'articles';
    protected $primaryKey = 'id';
    // public $timestamps = false;
    // protected $guarded = ['id'];
    protected $fillable = ['title', 'category_id'];
    // protected $hidden = [];
    // protected $dates = [];

    /*
    |--------------------------------------------------------------------------
    | FUNCTIONS
    |--------------------------------------------------------------------------
    */

    /*
    |--------------------------------------------------------------------------
    | RELATIONS
    |--------------------------------------------------------------------------
    */

    public function category(){
        return $this->belongsTo('App\Models\Category');
    }
}

我在这两个模型之间建立了联系。因此,当我创建Article时,它会显示标题,我必须从category_id中选择category select

所有这些之后,我制作了Archive表,这些是我的迁移:

Schema::create('archives', function (Blueprint $table) {
   $table->increments('id');
   $table->string('title');

   $table->bigInteger('category_id')->unsigned();
   $table->foreign('category_id')->references('id')->on('categories');

   $table->bigInteger('article_id')->unsigned();
   $table->foreign('article_id')->references('id')->on('articles');

   $table->timestamps();
});

还有我的Archive.php模型:

class Archive extends Model
{
    use CrudTrait;

    /*
    |--------------------------------------------------------------------------
    | GLOBAL VARIABLES
    |--------------------------------------------------------------------------
    */

    protected $table = 'archives';
    protected $primaryKey = 'id';
    // public $timestamps = false;
    // protected $guarded = ['id'];
    protected $fillable = ['title', 'category', 'article'];
    // protected $hidden = [];
    // protected $dates = [];

    /*
    |--------------------------------------------------------------------------
    | FUNCTIONS
    |--------------------------------------------------------------------------
    */

    /*
    |--------------------------------------------------------------------------
    | RELATIONS
    |--------------------------------------------------------------------------
    */

    public function category(){
        return $this->belongsTo('App\Models\Category');
    }

    public function article(){
        return $this->belongsTo('App\Models\Article');
    }
}

然后,我按照backpack docs的指示进行操作。 这是我的ArchiveCrudController

public function setup()
    {
        /*
        |--------------------------------------------------------------------------
        | CrudPanel Basic Information
        |--------------------------------------------------------------------------
        */
        $this->crud->setModel('App\Models\Archive');
        $this->crud->setRoute(config('backpack.base.route_prefix') . '/archive');
        $this->crud->setEntityNameStrings('archive', 'archives');

        $this->crud->setColumns(['title', 'category', 'article']);
        $this->crud->addField([
            'name' => 'title',
            'type' => 'text',
            'label' => "Archive title"
        ]);

        $this->crud->addField([    // SELECT2
            'label'         => 'Category',
            'type'          => 'select',
            'name'          => 'category_id',
            'entity'        => 'category',
            'attribute'     => 'title',
        ]);
        $this->crud->addField([ // select2_from_ajax: 1-n relationship
            'label'                => "Article", // Table column heading
            'type'                 => 'select2_from_ajax',
            'name'                 => 'article_id', // the column that contains the ID of that connected entity;
            'entity'               => 'article', // the method that defines the relationship in your Model
            'attribute'            => 'title', // foreign key attribute that is shown to user
            'data_source'          => url('api/article'), // url to controller search function (with /{id} should return model)
            'placeholder'          => 'Select an article', // placeholder for the select
            'minimum_input_length' => 0, // minimum characters to type before querying results
            'dependencies'         => ['category'], // when a dependency changes, this select2 is reset to null
            //'method'                    => ‘GET’, // optional - HTTP method to use for the AJAX call (GET, POST)
        ]);


        /*
        |--------------------------------------------------------------------------
        | CrudPanel Configuration
        |--------------------------------------------------------------------------
        */

        // TODO: remove setFromDb() and manually define Fields and Columns
        //$this->crud->setFromDb();

        // add asterisk for fields that are required in ArchiveRequest
        $this->crud->setRequiredFields(StoreRequest::class, 'create');
        $this->crud->setRequiredFields(UpdateRequest::class, 'edit');
    }

类似于backpack docs。然后我在Api中创建了App\Http\Controller文件夹,然后在其中创建了ArticleController,如下所示:

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Article;
use Illuminate\Http\Request;

class ArticleController extends Controller
{
    public function index(Request $request)
    {
        $search_term = $request->input('q');
        $form = collect($request->input('form'))->pluck('value', 'name');

        $options = Article::query();

        // if no category has been selected, show no options
        if (! $form['category']) {
            return [];
        }

        // if a category has been selected, only show articles in that category
        if ($form['category']) {
            $options = $options->where('category_id', $form['category']);
        }

        if ($search_term) {
            $results = $options->where('title', 'LIKE', '%'.$search_term.'%')->paginate(10);
        } else {
            $results = $options->paginate(10);
        }

        return $options->paginate(10);
    }

    public function show($id)
    {
        return Article::find($id);
    }
}

我只是从docs复制粘贴代码,但是我当然根据需要更改了模型。 最后是我的routes

Route::get('api/article', 'App\Http\Controllers\Api\ArticleController@index');
Route::get('api/article/{id}', 'App\Http\Controllers\Api\ArticleController@show');

我将这些路由复制粘贴到web.php文件夹中的routescustom.php文件夹中的routes/backpack中。

但是当我在Archive create中选择类别时,没有articles显示。 有人可以帮我吗?

enter image description here

2 个答案:

答案 0 :(得分:0)

您的代码中有一些问题,希望这可以解决它们:

1-在ArchiveCrudController中:确保具有category_id的依赖项不是category ...

'dependencies'         => ['category_id'], 

 $this->crud->addField([ // select2_from_ajax: 1-n relationship
            'label'                => "Article", 
            'type'                 => 'select2_from_ajax',
            'name'                 => 'article_id',
            'entity'               => 'article',
            'attribute'            => 'title', 
            'data_source'          => url('api/article'), 
            'placeholder'          => 'Select an article',
            'minimum_input_length' => 0, querying results
            'dependencies'         => ['category_id'], 
            //'method'                    => ‘GET’,
        ]);

2-在存档模型$ fillable中,应该使用db列名而不是关系...

 protected $fillable = ['title', 'category_id', 'article_id'];

3-同样,当您获得$ form请求参数时,它也带有名称category_id,就像您在Crud not(category)中命名一样

public function index(Request $request)
    {
        $search_term = $request->input('q');
        $form = collect($request->input('form'))->pluck('value', 'name');

        $options = Article::query();

        // if no category has been selected, show no options
        if (! $form['category_id']) {
            return [];
        }

        // if a category has been selected, only show articles in that category
        if ($form['category_id']) {
            $options = $options->where('category_id', $form['category_id']);
        }

        if ($search_term) {
            $results = $options->where('title', 'LIKE', '%'.$search_term.'%')->paginate(10);
        } else {
            $results = $options->paginate(10);
        }

        return $options->paginate(10);
    }

答案 1 :(得分:0)

在背包4.1中,您应在相关字段中添加'include_all_form_fields'=> true属性。