传递给Illuminate \ Database \ Eloquent \ Relations \ HasOneOrMany :: save()的参数1必须是Illuminate \ Database \ Eloquent \ Model的实例,

时间:2019-12-12 02:35:28

标签: php laravel eloquent

尝试在save one-to-one relationshipExpense之间进行ExpenseCategory并收到类似上面的错误

  

传递给Illuminate \ Database \ Eloquent \ Relations \ HasOneOrMany :: save()的参数1必须是Illuminate \ Database \ Eloquent \ Model的实例,给定为null,在/ home / z3r0 / Desktop / Kiyoi / laravel-中调用第88行的kiyoi / app / Http / Controllers / V1 / ExpenseController.php

我尝试了google和所有方法,但还是没有运气。

费用模型

    public function expense_category()
    {
        return $this->hasOne(\App\ExpenseCategory::class);
    }

在ExpenseCategory模型中

    protected $fillable = ['expense_id', 'code', 'name', 'description'];

    public function expense()
    {
        return $this->belongsTo(\App\Expense::class, 'expense_id');
    }

在ExpenseController中

    public function update(Request $request, $id)
    {
        $request->validate([
            'date' => 'required',
            'amount' => 'required',
        ]);

        $expense = Expense::findOrFail($id);
        $expense->user_id = auth()->user()->id;
        $expense->date = $request->date;
        $expense->description = $request->description;
        $expense->amount = $request->amount;
        $expense->expense_for = $request->expense_for;
        $expense->save();

        $expense_category = \App\ExpenseCategory::findOrFail($id);
        $expense_category->name = $request->name;
        $expense->expense_category()->save($request->expense_category);

        return response()->json([
            'updated' => true,
        ]);
    }

感谢您的帮助。谢谢...

1 个答案:

答案 0 :(得分:1)

您有错字。您要将$request->expense_category传递到save()方法中,但您打算传递$expense_category

更改

$expense->expense_category()->save($request->expense_category);

$expense->expense_category()->save($expense_category);