我正在尝试创建一个标记系统,现在我得到了两个表格,如下图所示
标签
我想基于`tag_id来标记Journal
和id
。但是,日记总是在taggables表中创建新记录。
这是我的模特关系
标签
class Tag extends Model
{
public function purchases()
{
return $this
->morphedByMany('Purchase', 'taggable');
}
public function taggables()
{
return $this->hasMany('Taggable');
}
}
购买
class Purchase extends Model
{
public function tags()
{
return $this
->morphToMany('Tag', 'taggable');
}
}
日记
class Journal extends Model
{
public function tags()
{
return $this
->morphToMany('Tag', 'taggable');
}
}
答案 0 :(得分:0)
如果我正确理解,您正在尝试同时将标签用于日记帐和采购。
然后您的表结构应类似于:
新闻(id,...)
购买(编号,...)
标签(ID,名称)
taggables (id,tag_id,taggable_id,taggable_type)
然后可以标记的模型都应具有检索其标记的方法:
app / Journal.php
// namespace and use statements
class Journal extends Model
{
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable');
}
}
app / Purchase.php
// namespace and use statements
class Purchase extends Model
{
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable');
}
}
可以同时应用于“购买”和“日记帐”的标签模型应具有N种方法,其中N是通过多态关系连接的不同模型的数量,在此示例中,N = 2(一种从中检索购买的方法标签,以及从标签中检索日记的一种方法。
app / Tag.php
// namespace and use statements
class Tag extends Model
{
public function journals()
{
return $this->morphedByMany('App\Journals', 'taggable');
}
public function purchases()
{
return $this->morphedByMany('App\Purchase', 'taggable');
}
}
设置关系后,您可以检索分配给日记帐或采购的标签:
$journal = \App\Journal::first();
foreach ($journal->tags as $tag) {
// ...
}
或检索链接到特定标签的所有日记帐或采购:
$tag = \App\Tag::first();
// $tag->journals will contain the journals model instances linked to the current tag
// $tag->purchases will contain the purchases model instances linked to the current tag
注意:要定义关系,请使用相关类的FQDN,例如:'App\Tag'
而不是'Tag'
,否则自动加载器将找不到该类。