我想用这段代码显示过去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();
});
标签表和标签之间需要什么关系?如何在视图中访问标签名称?如果我使用belongsTo关系:
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
]
最初我建议taggable实体的tags()关系名称应该只是tag()。
那么Taggable实体应该有这样的“id”:
Schema::create('taggables', function (Blueprint $table) {
$table->increments('id');
$table->integer('tag_id');
$table->integer('taggable_id');
$table->string('taggable_type');
$table->timestamps();
});
最后,Taggable实体应该具有这样的多态关系:
/**
* @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;
}
不要忘记添加到与Taggable相关的其他实体:
/**
* @return \Illuminate\Database\Eloquent\Relations\morphMany
*/
public function taggables()
{
return $this->morphMany(Taggable::class, 'taggable');
}
像这样使用Taggable关系:
$anyOtherModel->taggables()->create([
'tag_id' => $tag->id,
]);