如何使用jQuery添加多个select2并循环遍历产品

时间:2019-05-29 22:44:11

标签: laravel jquery-select2 laravel-5.8 voyager

我使用Voyager管理面板1.2.2版重新安装了Laravel 5.8,在该版本中,我覆盖了产品的BREAD,以便用户选择“关联产品”。我有与复选框一起使用的代码,但是有2000多种产品,我想使其与select2和jquery一起使用,以便它循环遍历数据库中的产品,并允许从数据透视表建立产品关联。

class Product extends Model
{
    public function groups(){
      return $this->belongsToMany('App\Group');
    }
    public function categoriesCards(){
      return $this->belongsToMany('App\CategoryCard');
    }
    public function associated() {
      return $this->belongsToMany(Product::class, 'product_assocs', 'product_id_primary', 'product_id_assoc')->orWhere('product_id_assoc', $this->id);;
    }
    public function related() {
      return $this->belongsToMany(Product::class, 'product_assocs', 'product_id_assoc', 'product_id_primary');
    }
}
class ProductAssoc extends Model
{
  protected $table = 'product_assocs';
  protected $fillable = ['product_id_primary', 'product_id_assoc'];
  public function products()
  {
      return $this->belongsTo('App\Product');
  }
}

class Select2AutocompleteController extends Controller
{
    /**
     * Show the application layout.
     *
     * @return \Illuminate\Http\Response
     */

    public function layout()
    {
        return view('select2');
    }
    /**
     * Show the application dataAjax.
     *
     * @return \Illuminate\Http\Response
     */
    public function dataAjax(Request $request)
    {
        $data = [];

        if($request->has('q')){
            $search = $request->q;
            $data = DB::table("products")
                    ->select("id","style_number","name")
                    ->where('name','LIKE',"%$search%")
                    ->get();
        }

        return response()->json($data);
    }
}

Route::get('select2-autocomplete', 'Select2AutocompleteController@layout');
Route::get('select2-autocomplete-ajax', 'Select2AutocompleteController@dataAjax');

                  <select name="association[]" style="margin-right:5px;" id="select2-multi" class="form-control select2-multi" multiple>
                    @foreach ($allAssociations as $product)
                    <option value="{{ $product->id }}" selected> {{ $product->style_number }} - {{ $product->name }}</option>
                    @endforeach
                  </select>

以某种方式,多选框不会加载已经从数据库中选择的关联,它不允许您选择和分配新的关联。

0 个答案:

没有答案