将数据插入数据透视表中的其他属性

时间:2017-10-31 12:03:31

标签: php laravel

我有一个表peoples countries和一个数据透视表country_people。数据透视表具有属性countries_id peoples_id number。我可以将外键插入数据透视表,但我无法插入数字。我该怎么做呢 ?

人物模型

 public function countries()
    {
        return $this->belongsToMany('App\Country')->withPivot('number')
        ->withTimestamps();
    }

国家/地区模型

public function peoples()
    {
        return $this->belongsToMany('App\People')->withPivot('number')
        ->withTimestamps();
    }

控制器

   $people = new People(array(
        'quantity' => $request->get('quantity'),

    ));

    $people->save();
    $order->countries()->sync($request->get('id')->attach('quantity'));

2 个答案:

答案 0 :(得分:0)

看起来你正在组合更新方法。查看https://laravel.com/docs/5.5/eloquent-relationships#updating-many-to-many-relationships了解详情。

在您的情况下,请尝试:

  

$ order-> countries() - > attach($ request-> get('id'),['number'=>   $人民[ '量']);

如果要同步而不是附加,请使用:

  

$ order-> countries() - > sync([$ request-> get('id')=> ['number'=>   $人民[ '数量']]);

答案 1 :(得分:0)

如果要将其他列附加到数据透视表,则可以将其作为数组传递。例如:

$id = intval($request->get('id'));        
$order->countries()->sync( $id => ['number' => $quantity]);  //assuming you have saved the value of number in quantity

查看同步关联下的https://laravel.com/docs/5.5/eloquent-relationships以获取更多详细信息。

另外,请记住,如果未在数组中指定,则使用sync将删除任何先前的关系。如果您不希望这种情况发生,请使用syncWithoutDetaching。

相关问题