在表单中,我有一个标记字段,它只是一个标准文本字段。用户可以键入标签名,并将其添加到文章中。
我已经有了三个表:tags
、taggables
和articles
,考虑到我要求的前一个问题设置,它们是通过雄辩的关系方法链接起来的。
这是我在ArticleController
中的更新方法
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$validatedData = $request->validate([
'title' => 'required',
'excerpt' => 'required',
]);
$article = Article::find($id);
$article->title = $request->get('title');
$article->author = $request->get('author');
$article->category = $request->get('category');
$article->excerpt = $request->get('excerpt');
$article->content = $request->get('content');
$article->featuredImage = $request->get('featuredImage');
$article->featuredVideo = $request->get('featuredVideo');
$article->readingTime = $request->get('readingTime');
$article->published = $request->get('published');
$article->save();
/**
* Once the article has been saved, we deal with the tag logic.
* Grab the tag or tags from the field, sync them with the article
*/
$tags = $request->get('tags');
$comma = ',';
if (!empty($tags)) {
if (strpos($tags, $comma) !== false) {
$tagList = explode(",", $tags);
// Loop through the tag array that we just created
foreach ($tagList as $tags) {
// Get any existing tags
$tag = Tag::where('name', '=', $tags)->first();
// If the tag exists, sync it, otherwise create it
if ($tag != null) {
$article->tags()->sync($tag->id);
} else {
$tag = new Tag();
$tag->name = $tags;
$tag->slug = str_slug($tags);
$tag->save();
$article->tags()->sync($tag->id);
}
}
} else {
// Only one tag
$tag = Tag::where('name', '=', $tags)->first();
if ($tag != null) {
$article->tags()->sync($tag->id);
} else {
$tag = new Tag();
$tag->name = $tags;
$tag->slug = str_slug($tags);
$tag->save();
$article->tags()->sync($tag->id);
}
}
}
return back();
return redirect()->back();
}
在此方法中查找标记的部分中,我执行以下操作:
explode()
将字符串转换为数组。这种方法让人觉得很混乱,但是,我有没有办法让这个变得更干净呢?
是一个更新,给定提供的答案
我采用了以下方法:
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validatedData = $request->validate([
'title' => 'required',
'excerpt' => 'required',
]);
$article = new Article();
$article->title = $request->get('title');
$article->author = $request->get('author');
$article->category = $request->get('category');
$article->excerpt = $request->get('excerpt');
$article->content = $request->get('content');
$article->featuredImage = $request->get('featuredImage');
$article->featuredVideo = $request->get('featuredVideo');
$article->readingTime = $request->get('readingTime');
$article->published = $request->get('published');
//If no featured image set, automatically create featured image placeholder
if ($request->get('featuredImage') == null) {
$article->featuredImage = "http://via.placeholder.com/350x150";
}
$article->save();
// Handle Tags
$tags = $request->get('tags');
if (!empty($tags)) {
$tagList = array_filter(explode(",", $tags));
// Loop through the tag array that we just created
foreach ($tagList as $tags) {
$tag = Tag::firstOrCreate(['name' => $tags, 'slug' => str_slug($tags)]);
}
$tags = Tag::whereIn('name', $tagList)->get()->pluck('id');
$article->tags()->sync($tags);
}
return redirect('editable/news-and-updates')->with('success', 'Article has been added');
}
然后,为了在更新时显示这些标记,我执行了以下操作:
/**
* Show the form to edit this resource
*/
public function edit($id)
{
$user = auth::user();
$article = Article::find($id);
// Get the tags associated with this article and convert to a comma seperated string
if ($article->has('tags')) {
$tags = $article->tags->pluck('name')->toArray();
$tags = implode(', ', $tags);
} else {
$tags = "";
}
return view('editable.news.edit', compact('article', 'user', 'tags'));
}
本质上,我只是获取与本文相关的标记,将它们转换为数组,然后使用implode()
。
这使我在标记字段中将标记作为逗号分隔列表,如下所示:
blue, red, orange
但是,在更新时,如果我试图使用字段中相同的标记进行保存,则会得到:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'sauce' for key 'tags_slug_unique' (SQL: insert into
tags(
name,
slug,
updated_at,
created_at) values ( sauce, sauce, 2018-05-26 11:42:17, 2018-05-26 11:42:17))
下面是标记迁移以供参考:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTagsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('slug')->unique();
$table->timestamps();
});
Schema::create('taggables', function (Blueprint $table) {
$table->increments('id');
$table->integer('tag_id')->unsigned();
$table->integer('taggable_id')->unsigned();
$table->string('taggable_type');
$table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('taggables');
Schema::dropIfExists('tags');
}
}
发布于 2018-05-25 13:12:49
也许像这样的东西,只是从头部输入,没有测试,但我希望它能给你一个想法。
public function update(Request $request, Article $article)
{
$validatedData = $request->validate([
'title' => 'required',
'excerpt' => 'required',
// Make validation for all inputs !
]);
// Fill model with inputs and save (make sure that inputs are in fillable model property)
$article->fill($request->all())->save();
// Handle Tags
$this->handleTags($request, $article);
// Return Redirect to previous URL
return redirect()->back();
}
/**
* Handle Tags for Article
* @param \Illuminate\Http\Request $request
* @param \App\Article $article
* @return void
*/
public function handleTags(Request $request, Article $article){
/**
* Once the article has been saved, we deal with the tag logic.
* Grab the tag or tags from the field, sync them with the article
*/
$tagsNames = explode(',', $request->get('tags'));
// Create all tags (unassociet)
foreach($tagsNames as $tagName){
Tag::firstOrCreate(['name' => $tagName, 'slug' => str_slug($tagName)])->save();
}
// Once all tags are created we can query them
$tags = Tag::whereIn('name', $tagsNames)->get()->pluck('id')->get();
$article->tags()->sync($tags);
}
发布于 2018-05-25 13:07:19
没有必要检查是否有逗号,是否有两个不同的路径。如果没有逗号,iterate将返回一个元素来迭代。你可以直接删除if和remove。
$tagList = explode(",", $tags);
// Loop through the tag array that we just created
foreach ($tagList as $tags) {
// Get any existing tags
$tag = Tag::where('name', '=', $tags)->first();
// If the tag exists, sync it, otherwise create it
if ($tag != null) {
$article->tags()->sync($tag->id);
} else {
$tag = new Tag();
$tag->name = $tags;
$tag->slug = str_slug($tags);
$tag->save();
$article->tags()->sync($tag->id);
}
}
此外,还可以执行firstOrCreate
,您可以看到这里的文档。
firstOrCreate方法将尝试使用给定的列/值对来定位数据库记录。如果在数据库中找不到模型,则将插入一个记录,其中包含来自第一个参数的属性以及可选的第二个参数中的属性。
这可用于将代码重构为以下内容:
$tagList = explode(",", $tags);
// Loop through the tag array that we just created
foreach ($tagList as $tags) {
$tag = Tag::firstOrCreate(['slug' => $tags];
}
$tags = Tag::whereIn('name', $tagList)->get()->pluck('id')->get();
$article->tags()->sync($tags);
发布于 2019-06-07 06:11:07
我认为最简单的方法是使用多到多的多态关系.morphedByMany()
和morphToMany()
.看这个例子代码..。
在迁移中,它们有3个表(
articles
、tags
、taggables
)。
# --- for Article Table ---
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
// ---
});
}
# --- for Tags Table ---
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->increments('id');
$table->string('tagname');
});
}
# --- for Taggables Table ---
public function up()
{
Schema::create('taggables', function (Blueprint $table) {
$table->integer('tag_id');
$table->integer('taggable_id'); // for storing Article ID's
$table->string('taggable_type'); // Aside from Article, if you decide to use tags on other model eg. Videos, ...
});
}
在模型中
# Tag.php Model
class Tag extends Model
{
protected $fillable = [
'tagname',
];
public function article()
{
return $this->morphedByMany('Yourapp\Article', 'taggable');
}
}
# Article.php Model
class Article extends Model
{
protected $fillable = [
'title',
# and more...
];
public function tags()
{
return $this->morphToMany('Yourapp\Tag', 'taggable');
}
}
在AppServiceProvide.php ~ Yourapp/app/Providers/AppServiceProvider.php中
public function boot()
{
//... by creating this map you don't need to store the "Yourapp\Post" to the "taggable_type" on taggable table
Relation::morphMap([
'article' => 'Yourapp\Article',
'videos' => 'Yourapp\Videos', // <--- other models may have tags
]);
}
现在使用Elequent,您可以轻松地访问数据
$article->tags; # retrieve related tags for the article
$tags->articles; # or $tags->articles->get() retrieve all article that has specific tag
用于存储和更新文章
# SAVING article with tags
public function store(Request $request)
{
$validatedData = $request->validate([
'title' => 'required',
//----
// Validate tags and also it should be an Array but its up to you
'tag' => 'required|array|exists:tags,id' # < (exist:tags,id) This will check if tag exist on the Tag table
]);
$article = Article::create([
'title' => $request->input('title'),
//----
]);
//Adding tags to article, Sync() the easy way
$article->tags()->sync($request->input('tag'));
return "Return anywhare";
}
# UPDATE tags article
public function update(Request $request, $id)
{
// Validate first and ...
$article = Article::find($id)->first();
$article->title = $request->input('title');
$article->save();
//Updating tags of the article, Sync() the easy way
$article->tags()->sync($request->input('tag'));
return "Return anywhare";
}
有关多到多多态关系的更多详细信息信息
https://stackoverflow.com/questions/50529715
复制相似问题