laravel 在整数上调用成员函数 category()

La *_*oix 0 php many-to-many laravel-5

我正在尝试更新数据透视表中的现有记录,以便与 laravel 建立多对多的关系。

我有商店功能可以工作:

public function store(Request $request)
{
    $produk = new product($request->input()) ;

    $feat = (boolean)$request->input('featured');
    $input = $request->all();
    $input['featured'] = $feat;

    $inputproduk = product::create($input);
    $inputproduk->categories()->attach($request->input('kat_id'));
    return redirect()->back()->with('message', 'Memasukkan Data Produk Berhasil');
}
Run Code Online (Sandbox Code Playgroud)

但是为什么我的更新功能不起作用???

public function update(Request $request, $id)
{
    $produk = Product::FindorFail($id);

    $produk = new product($request->input()) ;

    $input = $request->except('_method', '_token', 'picture', 'kat_id');
    $inputproduk = product::whereId($id)->update($input);
    $inputproduk->categories()->sync($request->input('kat_id'));

    return redirect()->back()->with('message', 'Mengedit Data Produk Berhasil');

}
Run Code Online (Sandbox Code Playgroud)

错误是:

在整数上调用成员函数 category()

那什么意识?请帮我。

看法 :

        <div class="form-group">
          <label for="KategoriProduk">Kategori Produk</label>
          <select class="form-control" name="kat_id[]" multiple>
            @foreach($kategoris as $value)
              <option value="{{$value->id}}">{{$value->namekat}}</option>
            @endforeach
          </select>
        </div>
Run Code Online (Sandbox Code Playgroud)

我只发布部分内容,因为如果我全部发布,那么问题就是充满了代码。告诉我你是否需要更多。

cha*_*fdo 5

这是因为以下行。

$inputproduk = product::whereId($id)->update($input);
Run Code Online (Sandbox Code Playgroud)

当您调用 update 时,它​​将返回一个integerproduct对象。

您可以做的是先获取产品,然后再进行更新。

$inputproduk = product::whereId($id)->first();
$inputproduk->update($input);
$inputproduk->categories()->sync($request->input('kat_id'));
Run Code Online (Sandbox Code Playgroud)