首页 > 解决方案 > Laravel 获取所有复选框,包括从带有附加列的数据透视表中选中

问题描述

我正在尝试从数据透视表中获取所有带有附加列的复选框。

型号:库存

class Stock extends Model
{
   public function products(){
    return $this->belongsToMany('App\Product','products_stock')->withPivot('qtySpent')->withTimestamps();
}
}

型号:产品

class Product extends Model
{
   public function stocks(){
    return $this->belongsToMany('App\Stock','products_stock')->withPivot('qtySpent')->withTimestamps();
}
}

枢轴:product_stock

Schema::create('product_stock', function (Blueprint $table) {
         $table->bigIncrements('id');        
    $table->integer('product_id');
    $table->foreign('product_id')
          ->references('id')
          ->on('products')->onDelete('cascade');
   
    $table->integer('stock_id');
    $table->foreign('stock_id')
          ->references('id')
          ->on('stocks')->onDelete('cascade');               
            $table->integer('qtySpent')->nullable();
            $table->timestamps();
    });

目前,我的数据透视表中有 2 条记录:

 id| product_id | stock_id | qtySpent
    =====================================
    1   1              1          100
    2   1              2          200

但是,在我的股票表中,我有 3 条记录:

 id| restaurant_id | name     | qty | qtyType
    =====================================
    1   16         Mozzarela    20    KG
    2   16         Olives       10    KG
    3   16         Beer         100   Liter

现在,我需要将所有这些股票记录显示为与 qtySpent(来自数据透视表)作为文本框链接的复选框。但是,要检查的数据透视表中的股票记录和与这些股票记录链接的 qtySpent 将填充它们的值。

目前我有这些代码来获取记录。

$thisRestaurantId = Auth::user()->sFor; 
@foreach (Product::where('toRes',$thisRestaurantId)->get() as $pro)
    @foreach(Stock::where('restaurant_id','=', $thisRestaurantId)->get() as $stock)
    <tr style="display: inline-grid;">
        <td>
            <input data-id="{{ $stock->id }}" type="checkbox" class="ingredient-enable"  {{ $pro->stocks->contains('pivot.stock_id', $stock->id) ? 'checked' : ''}} >
            <label class="form-check-label">{{$stock->name}}</label>
        </td>
        <td><input value="{{ $stock->pivot->qtySpent ?? null }}" {{ $pro->stocks->contains('pivot.qtySpent', $stock->id) ? null : 'disabled'  }} data-id="{{ $stock->id }}" name="stocks[{{ $stock->id }}]" type="text" class="ingredient-amount form-control" placeholder="Menge">
        </td>
    </tr>                                  
    @endforeach
@endforeach

此代码显示 3 个复选框(其中两个已选中),并显示 3 个空文本框。因此,qtySpent 值未显示为这 2 个选中的复选框(上方(stocks)作为复选框,底部(qtySpent)作为文本框)。

|✔| Mozzarela      |✔| Olives        |  | Beer
    
|    |             |    |           |      |

在这种情况下,结果应该是这样的:

|✔| Mozzarela      |✔| Olives        |  | Beer

|100  |             |200  |           |      |

先感谢您

标签: laravelcheckboxpivot-tablerelationship

解决方案


推荐阅读