【问题标题】:Laravel Illegal offset type on many to many with extra columnLaravel Illegal offset type on many to many with extra column
【发布时间】:2018-02-26 07:59:07
【问题描述】:

在数据库中,我有一个产品和组件表
我有一个多对多关系表,它是 component_product 它的属性为 (product_id,component_id,quantity)

在模型产品中

class Product extends Model
{
      protected $fillable = [
         'name','price','user_id','is_avilable','description'
     ];

     public function components()
     {
        return $this->belongsToMany('App\Component')
            ->withPivot('quantity');
     }
}

在视图中

{!! Form::select('component_id[]',$components,null !!}
{!! Form::select('component_id[]',$components,null !!}
{!! Form::number('quantity[]',null ]) !!}
{!! Form::number('quantity[]',null ]) !!}

在控制器中

public function store(Request $request)
{
         $product= Product::create( $request->all() );
         $product->components()->sync($request->component_id => ['quantity'=> $request->quantity ] );

}

它给了我一个非法偏移类型的错误

注意:如果转储 $request->quantity 或 $request->component_id 它将正确获取数组

【问题讨论】:

  • FWIW,我遇到了同样的问题,我收集了 User 实例。我挠着头想知道怎么了。 然后我阅读了文档。 它需要是一个ID 集合。故事的寓意:总是阅读文档

标签: laravel many-to-many


【解决方案1】:

这就是我解决自己问题的方法
在 Laravel 文档中

$user->roles()->sync([1 => ['expires' => true], 2, 3]);

所以要匹配这个

$manyToMany = array();
         for ( $i=0 ; $i< count($request->component_id); $i++ )
         {
            $manyToMany[ $request->component_id[$i] ] = ['quantity' =>$request->quantity[$i] ];
         }
         $product->components()->sync($manyToMany);

他们是更好的解决方案吗

【讨论】:

    【解决方案2】:

    laravel 文档中的同步示例 (https://laravel.com/docs/5.5/eloquent-relationships)

    $user->roles()->sync([1 => ['expires' => true], 2, 3]);
    

    尝试将, 更改为=&gt;

    所以在你的情况下:

    $product->components()->sync([$request->component_id => ['quantity'=> $request->quantity]]);
    

    【讨论】:

      猜你喜欢
      • 2019-04-20
      • 2016-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多