调用未定义的方法 Illuminate\Database\Query\Builder::tags()
Call to undefined method Illuminate\Database\Query\Builder::tags()
我在我的表单中有以下标签字段用于在博客中创建标签 post,因为博客标签可以与单个标签相关 post,我使用 select2这是我使用的输入字段:
{{ Form::label('tags', 'Tags:') }}
<select name="tags[]" class="form-control select2-multi" multiple="multiple">
@foreach($tags as $tag)
<option value="{{ $tag->id }}">{{ $tag->name }}</option>
@endforeach
</select>
这是数据验证然后存入数据库的函数
public function store(Request $request)
{
// -------- WORKFLOW HERE ------
// validate the data from the form
$this->validate($request,array(
'title' => 'required|max:255',
'slug ' => '|min:5|alpha_dash|max:255|unique:posts,slug|',
'category_id' => 'required|integer',
'body' => 'required'
)); // end of validation
// sotre that data into database
$post = new Post;
$post->title = $request->title;
$post->slug = $request->slug;
$post->category_id = $request->category_id;
$post->body = $request->body;
$post->save();
$post->tags()->sync('$request->tags',false);
Session::flash('success','Your Post has been Successful saved !');
// and then redirect the user to some page
return redirect()->route('posts.show',$post->id);
}
尝试保存 post 时出现以下错误
Call to undefined method Illuminate\Database\Query\Builder::tags()
标签型号
class Tag extends Model
{
public function post(){
return $this->belongsToMany('App\Post');
}
}
Table post_tag
的结构
在你的post模型中添加这个
public function tags()
{
return $this->hasMany(Tag::class,'id','post_id');
}
我在我的表单中有以下标签字段用于在博客中创建标签 post,因为博客标签可以与单个标签相关 post,我使用 select2这是我使用的输入字段:
{{ Form::label('tags', 'Tags:') }}
<select name="tags[]" class="form-control select2-multi" multiple="multiple">
@foreach($tags as $tag)
<option value="{{ $tag->id }}">{{ $tag->name }}</option>
@endforeach
</select>
这是数据验证然后存入数据库的函数
public function store(Request $request)
{
// -------- WORKFLOW HERE ------
// validate the data from the form
$this->validate($request,array(
'title' => 'required|max:255',
'slug ' => '|min:5|alpha_dash|max:255|unique:posts,slug|',
'category_id' => 'required|integer',
'body' => 'required'
)); // end of validation
// sotre that data into database
$post = new Post;
$post->title = $request->title;
$post->slug = $request->slug;
$post->category_id = $request->category_id;
$post->body = $request->body;
$post->save();
$post->tags()->sync('$request->tags',false);
Session::flash('success','Your Post has been Successful saved !');
// and then redirect the user to some page
return redirect()->route('posts.show',$post->id);
}
尝试保存 post 时出现以下错误
Call to undefined method Illuminate\Database\Query\Builder::tags()
标签型号
class Tag extends Model
{
public function post(){
return $this->belongsToMany('App\Post');
}
}
Table post_tag
在你的post模型中添加这个
public function tags()
{
return $this->hasMany(Tag::class,'id','post_id');
}