代码之家  ›  专栏  ›  技术社区  ›  slickness

从taggables加载标记

  •  0
  • slickness  · 技术社区  · 6 年前

    我想用以下代码显示过去4小时中最常用的4个标签:

    $topTags = Taggable::whereDate('created_at', '>=', now()->subHours(4))
        ->groupBy('tag_id')
        ->orderByRaw('count(tag_id) DESC'))
        ->take(4)
        ->with('tags')
        ->get();
    

    桌子

    Schema::create('tags', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name')->unique();
                $table->timestamps();
            });
    
     Schema::create('taggables', function (Blueprint $table) {
                $table->integer('tag_id');
                $table->integer('taggable_id');
                $table->string('taggable_type');
                $table->timestamps();
            });
    

    class Taggable extends Model
    {
        protected $fillable = ['tag_id', 'taggable_id', 'taggable_type'];
    
        public function tags()
        {
            return $this->belongsTo('App\Tag');
        }
    }
    

    标记数组为空:

     #relations: array:1 [▼
            "tags" => null
          ]
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Mesuti    6 年前

    最初,我建议Taggable实体的tags()关系名称应该是only tag()。

    那么可标记实体应该有自己的“id”,如下所示:

     Schema::create('taggables', function (Blueprint $table) {
                $table->increments('id');
                $table->integer('tag_id');
                $table->integer('taggable_id');
                $table->string('taggable_type');
                $table->timestamps();
        });
    

    最后,可标记实体应具有如下多态关系:

    /**
     * @return \Illuminate\Database\Eloquent\Relations\MorphTo
     */
    public function taggable()
    {
        return $this->morphTo();
    }
    
    public function tag()
    {
        return $this->belongsTo('App\Tag');
    }
    

    因此,您可以通过如下方式访问标记名:

    $topTags = Taggable::whereDate('created_at', '>=', now()->subHours(4))
        ->groupBy('tag_id')
        ->orderByRaw('count(tag_id) DESC'))
        ->take(4)
        ->with('tag')
        ->get();
    
    foreach($topTags as $ttag){
        $ttag->tag->name;
    }
    

    不要忘记添加到其他与标记相关的实体:

    /**
     * @return \Illuminate\Database\Eloquent\Relations\morphMany
     */
    public function taggables()
    {
        return $this->morphMany(Taggable::class, 'taggable');
    }
    

    标记关系的用法如下:

        $anyOtherModel->taggables()->create([
            'tag_id'     => $tag->id,
        ]);