【问题标题】:How should I approach making this form in Laravel 5.2?我应该如何在 Laravel 5.2 中制作这个表格?
【发布时间】:2018-02-07 17:50:41
【问题描述】:

当我开始这个项目时,我避免使用 Laravel 的表单助手,因为它看起来是一种复杂的方式来制作一个根本不会增加可读性的表单。我现在希望我有,因为模型表单绑定比我预期的要困难得多。

这个项目是一个博客网站,帖子已设置为与标签具有多对多关系(模型与表格模式一起发布在底部)。当我去编辑一篇文章时,我希望已经在字段中选择了与该文章关联的标签,并可以选择删除它们以及添加新标签。这是我必须开始的:

<div class="form-group">
    <select class="form-control select2-multi" name="tags[]" multiple="multiple">
        @foreach($post->tags as $tag)

            <option value="{{ $tag->id }}" selected>{{ $tag->name }}</option>

        @endforeach

        @foreach($tags as $tag)

            <option value="{{ $tag->id }}">{{ $tag->name }}</option>

        @endforeach
    </select>
</div>

我意识到我有一个问题,即按选择打印出来的标签也会在第二个 foreach 中打印出来。

此时我被难住了。对于该怎么做,我有两个想法,但我想遵循最佳做法,因此欢迎提出任何建议:

  1. 在控制器中使用过程编程从标签数组中删除任何与 $post->tags 标签匹配的标签,然后再将其传递给视图。

  2. 在标签控制器中创建一个方法,该方法构建一个查询以选择除了与作为参数传递的 ID 的帖子相关联的标签之外的所有标签。

我对可以执行此操作的 SQL 查询的想法(但我不确定如何在 eloquent 中执行此操作):

SELECT  *
FROM    tags
WHERE   id NOT IN(  SELECT  tag_id
                    FROM    posts INNER JOIN post_tag ON posts.id=post_tag.post_id)

我是不是让这个问题变得更复杂了?我应该只使用表单助手将数据绑定到我的表单吗?

--- 发布和标记模型以及数据库模式 ---

后模型

class Post extends Model
{
    protected $table    = 'posts';

    /**
     * Define relationship between posts and categories.
     *
     * @return eloquent relationship
     */
    public function category()
    {
        return $this->belongsTo('App\Category', 'category_id');
    }

    /**
     * Define relationship between posts and tags.
     *
     * @return eloquent relationship
     */
    public function tags()
    {
        return $this->belongsToMany('App\Tag', 'post_tag', 'post_id', 'tag_id');
    }
}

标签模型

class Tag extends Model
{
    protected $table    = "tags";
    public $timestamps  = false;

    public function posts()
    {
        return $this->belongsToMany('App\Post', 'post_tag', 'tag_id', 'post_id');
    }
}

架构

posts(id, title, body, slug, category_id, created_at, updated_at)
tags(id, name)
post_tag(id, post_id, tag_id)

【问题讨论】:

    标签: laravel-5 eloquent many-to-many


    【解决方案1】:

    这是我的建议。

    在你的控制器中

    public function edit(Post $post){
    
        $tags = Tag::all();
        $postTags = $post->tags->pluck('id')->toArray();
    
        return view('edit', compact('tags', 'postTags'));
    }
    

    在你的刀片中

    ...
    @foreach($tags as $tag)
    
        {{--We list all the tags--}}
    
        {{--While listing them, we check if the current tag is part of the tags belonging to this post--}}
    
        {{--If it belongs then we select it--}}
    
        <option value="{{ $tag->id }}" {{ in_array($tag->id, $postTags) ? "selected" : null }}>{{ $tag->name }}</option>
    
    @endforeach
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-17
      • 1970-01-01
      • 2022-01-13
      • 2017-11-26
      相关资源
      最近更新 更多