Laravel 存储方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45229945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:20:56  来源:igfitidea点击:

Laravel store method

phplaraveleloquent

提问by Sprunkas

I want to make store eloquent to be more simplified to something like this:

我想让 store eloquent 更简化为这样的事情:

$keyword = Keyword::create([
        'keyword'       => $request->input('keyword'),
        'micro_price'   => $request->input('micro_price'),
        'macro_price'   => $request->input('macro_price'),
        'cmd'           => $request->input('cmd'),
]);

Instead of this:

取而代之的是:

    $keyword = new Keyword;
    $keyword->keyword = $request->input('keyword');
    $keyword->micro_price = $request->input('micro_price');
    $keyword->macro_price = $request->input('macro_price');
    $keyword->cmd = $request->input('cmd');
    $keyword->user()->associate(Auth::user());
    $keyword->server()->associate($request->input('title'));
    $keyword->save();

But there is a problem that I have in keywordsdatabase table with 2 foreign keys (server_idand user_id) and I want that my eloquent model assign these 2 foreign keys properly, but I have no idea how to make that in simplified version.

但是我在带有 2 个外键 ( and ) 的关键字数据库表中存在一个问题,我希望我的雄辩模型正确分配这 2 个外键,但我不知道如何在简化版本中实现。server_iduser_id

Thanks in advance for help !

预先感谢您的帮助!

采纳答案by Alexey Mezenin

Use the mass assignmentfeature and all()request method:

使用批量分配功能和all()请求方法:

$keyword = Keyword::create($request->all());

It'll work if you'll define $fillableproperty in the Keywordmodel:

如果您$fillableKeyword模型中定义属性,它将起作用:

protected $fillable = ['keyword', 'cmd', 'micro_price', 'mini_price'];

If you need to associate a keyword with two models, you can define foreign keys manually:

如果需要将一个关键字与两个模型关联,可以手动定义外键:

$data = $request->all();
$data['user_id'] = auth()->id();
$data['server_id'] => $request->title;
$keyword = Keyword::create($data);

To associate an object with one model you can use relationship:

要将对象与一个模型相关联,您可以使用关系:

auth()->user()->keywords()->create($request->all());