使用单个表单 Laravel 将数据添加到多个表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44354671/
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
Adding Data to multiple tables with a single form Laravel
提问by Leo
I am trying to insert a blog post on db, I do have two tables posts and tags tables. When I insert the create the post I want to be able to insert the data from the form in those two different tables.
我正在尝试在 db 上插入一篇博客文章,我确实有两个表帖子和标签表。当我插入创建帖子时,我希望能够将表单中的数据插入这两个不同的表中。
create.blade.php;
create.blade.php;
<div class="account_grid">
<div class="col-md-6 login-right wow fadeInRight col-md-offset-3" data-wow-delay="0.4s">
<h3>CREATE A BLOG POST</h3>
<p>Please fill out the required fields *</p>
<form method="post" action="/posts" enctype="multipart/form-data">
{{csrf_field()}}
<div>
<span>Title:<label>*</label></span>
<input type="text" id="title" name="title" >
</div>
<div>
<span>Body<label>*</label></span>
<textarea id="body" name="body" rows="14" ></textarea>
</div>
<div>
<span>Tags:<label>*</label></span>
<input type="text" id="tags" name="tags">
</div>
<div>
<span>Image<label>*</label></span>
<input type="file" name="image" id="image" >
</div>
<input type="submit" value="Publish">
</form>
@include('layouts.errors')
</div>
<div class="clearfix"> </div>
</div>
On my route file I have the path that leads to PostsController.php which has a store method like below:
在我的路由文件中,我有通向 PostsController.php 的路径,它有一个如下所示的 store 方法:
PostsController.php
帖子控制器.php
public function store(Request $request){
$this->validate($request, [
'title' =>'required|max:48',
'body'=>'required',
'image'=>'required',
'tags' =>'required|max:200'
]);
$post = new Post;
$destination ='uploads';
$image = $request->file('image');
$filename = $image->getClientOriginalName();
$image->move($destination, $filename);
$location=$destination.'/'.$filename;
$tags = request('tags');
Post::create([
'title'=>request('title'),
'body' =>request('body'),
'user_id'=>auth()->id(),
'image' =>$destination.'/'.$filename
]);
$tag = new Tag;
Tag::create([
'name' => $tags
]);
return redirect('/blog');
}
}
The thing is that when I call the method I want the form data to be saved on two different tables, I have tried like below but I am getting ERROR:
问题是,当我调用该方法时,我希望将表单数据保存在两个不同的表中,我尝试过如下所示,但出现错误:
MassAssignmentException in Model.php line 232: name
Model.php 第 232 行中的 MassAssignmentException:名称
I did research the issue but no luck; and yes I do have the 'name' listed in the protected $fillable array. Any suggestion on how to store data in two different tables or what type of relationship should i use.
我确实研究过这个问题,但没有运气;是的,我确实在受保护的 $fillable 数组中列出了“名称”。关于如何将数据存储在两个不同的表中或我应该使用什么类型的关系的任何建议。
On post.php model i do have a relationship specified. Tags belongsToMany as well as on my tag.php model Post belongsToMany
在 post.php 模型上,我确实指定了一个关系。标签belongsToMany 以及在我的tag.php 模型上发布belongsToMany
p.s New to Laravel.
ps Laravel 新手。
tag.php model:
tag.php 模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
//
public function posts(){
return $this->belongsToMany(Post::class);
}
public function getRouteKeyName(){
return 'name';
}
}
Post.php model:
Post.php 模型:
<?php
namespace App;
use Carbon\Carbon;
class Post extends Model
{
public function comments(){
return $this->hasMany(Comment::class);
}
public function addComment($body, $name, $email, $user_id){
$this->comments()->create(compact('body','name','email', 'user_id'));
}
public function user(){ // $comment->user->name
return $this->belongsTo(User::class);
}
public function scopeFilter($query, $filters){
if($month =$filters['month']){
//
$query->whereMonth('created_at', Carbon::parse($month)->month);
}
if($year = $filters['year']){
$query->whereYear('created_at',$year );
}
}
public static function archives(){
return static:: selectRaw('year(created_at)year, monthname(created_at)month, count(*) published')
->groupBy('year','month')
->orderByRaw('min(created_at) desc')
->get()
->toArray();
}
public function tags(){
return $this->belongsToMany(Tag::class);
}
}
回答by Sandeesh
Based on the comments and discussion you have a couple of issues. The original MassAssignmentException
was due to the fact that you have a custom base model in which you define a single $fillable
property for all the models. But you still referenced the default Eloquent model when extending your Tag
model.
根据评论和讨论,您有几个问题。最初MassAssignmentException
是因为您有一个自定义基本模型,您可以在其中$fillable
为所有模型定义一个属性。但是您在扩展模型时仍然引用了默认的 EloquentTag
模型。
Then the next issue would be attaching the tags to the post. You're passing a space delimited tag value and you're planning to separate them when accessing. That's not how tags work when you use many-to-many relationship. You need to split the tags up before storing them and attach each one to the post.
然后下一个问题是将标签附加到帖子上。您正在传递一个以空格分隔的标签值,并且您计划在访问时将它们分开。当您使用多对多关系时,这不是标签的工作方式。您需要在存储标签之前将它们分开并将每个标签附加到帖子中。
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required|max:48',
'body' => 'required',
'image' => 'required',
'tags' => 'required|max:200'
]);
$destination = 'uploads';
$image = $request->file('image');
$filename = $image->getClientOriginalName();
$image->move($destination, $filename);
$location = $destination . '/' . $filename;
$post = Post::create([
'title' => request('title'),
'body' => request('body'),
'user_id' => auth()->id(),
'image' => $location
]);
$tags = explode(' ', request('tags'));
$tagInstances = [];
foreach($tags as $tag) {
$tagInstances[] = new Tag(['name' => $tag]);
}
$post->tags()->saveMany($tagInstances);
return redirect('/blog');
}
回答by Nimeshika Prabodhani
I solve this exception and this exception throws when you have not define $table and $fillable in your each model separately.
我解决了这个异常,当你没有在你的每个模型中分别定义 $table 和 $fillable 时,这个异常就会抛出。
protected $table = 'table_name';
受保护的 $table = 'table_name';
protected $fillable = [fields which you define in your table];
protected $fillable = [您在表格中定义的字段];
visit https://laravel.com/docs/5.0/eloquent#mass-assignmentthen you can get clear understanding about this
访问https://laravel.com/docs/5.0/eloquent#mass-assignment然后你可以清楚地了解这个
回答by Vandemberg Lima
Step 1:Check your model and database. See the Tag struct table, if it has the column name.
第 1 步:检查您的模型和数据库。查看标签结构表,如果它有列名。
Step 2:To insert data with Eloquent::create
you need to create one variable called fillable
, in which you pass the fields that you want created in your table. Look at the example:
第 2 步:要插入数据,Eloquent::create
您需要创建一个名为 的变量fillable
,您可以在其中传递要在表中创建的字段。看例子:
class Flight extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name'];
}
With that you can insert in your database, you can use other approach to insert which goes something like this
有了它,您可以在数据库中插入,您可以使用其他方法来插入,就像这样
$your_table = new YourTable();
$your_table->attr = "hello world";
$your_table->save();
Also, you don't need to create the variable new Post and after call Post::create
. You can call only Post::create
.
此外,您不需要创建变量 new Post 和 after call Post::create
。你只能打电话Post::create
。
See the Laravel Eloquent doc: https://laravel.com/docs/5.4/eloquent
请参阅 Laravel Eloquent 文档:https://laravel.com/docs/5.4/eloquent
回答by Brijesh Dubey
Just declare Protected $fillable =['column 1','column 2'];
只需声明 Protected $fillable =['column 1','column 2'];
$fillable variable use for create method for insterting data. If you are using create method to insert data then you must specify $fillable variable in model class
$fillable 变量用于插入数据的创建方法。如果您使用 create 方法插入数据,则必须在模型类中指定 $fillable 变量
In $fillable variable, you specify specific column which you want to allow to insert data in table
在 $fillable 变量中,您指定要允许在表中插入数据的特定列
I think your issue in
我认为你的问题在
- Either you are not declare $fillable variable or
- You are not specify column in $fillable which you want to insert.
- 要么您没有声明 $fillable 变量,要么
- 您没有在 $fillable 中指定要插入的列。