eloquent Model::create() 的特定 $fillable 和 Model->update() 的另一个 $fillable

eloquent specific $fillable for Model::create() and another $fillable for Model->update()

我需要一种方法来仅在创建 Article 模型时设置 ArticleCategory,而不是通过使用 $fillable 数组的更新过程进行更改。我需要记住以下几点:

1- 我想通过批量分配来做到这一点 2- 我使用表单请求验证进行验证

那么是否有用于创建的 $fillable 数组和用于更新的 $fillable 数组?

谢谢...

只有一个fillable属性,所以你想要的默认是不可能的

但您可以使用 only 并只检索要更新的输入:

来自文档:

If you need to retrieve a subset of the input data, you may use the only and except methods. Both of these methods accept a single array or a dynamic list of arguments:

$input = $request->only('username', 'password');

$input = $request->except(['credit_card']);

在你的情况下它会是这样的:

public function update(UpdateArticleRequest $request, $id)
{
    $article = Article::findOrFail($id);
    $article->update($request->only('title', 'name'));
}

你不能真的那样做,但你可以考虑以下替代方案:

不要将 ArticleCategory 放入您的 $fillable 数组中。

使用以下内容:

 $article = new Article($request->all());
 $article->ArticleCategory = $request->input('ArticleCategory');
 $article->save();

这样您就可以在需要时明确设置文章类别并保护它免于批量分配。

我认为这是解决这个问题的明智方法,因为(从它的声音来看)ArticleCategory 通常应该受到保护。