因此,我尝试创建一个 taggable
表,使多个 models
具有与其关联的标签,并认为 Laravel 的 Polymorphic relationships将是要走的路。
不幸的是,我似乎无法让它们在以下设置中工作。当我运行 php artisan migrate:refresh --seed 时收到以下错误。
{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"Class name must be a valid object or a string","file":"...\\vendor\\laravel\\framework\\src\\
Illuminate\\Database\\Eloquent\\Model.php","line":527}}
我认为该问题是由于 Taggable
模型具有相同的 morphTo
命名的,如下所述。由于更改此解决了问题。为什么这会导致问题?
可标记模型
class Taggable extends Eloquent {
protected $table = 'taggable';
public function taggable()
{
return $this->morphTo();
}
}
轨道模型
class Track extends Eloquent {
protected $table = 'tracks';
protected $fillable = array('title', 'year', 'image');
protected $guarded = array('id');
public function playlists()
{
return $this->belongsToMany('Playlist');
}
public function tags()
{
return $this->morphMany('Taggable', 'taggable');
}
}
标记模型
class Tag extends Eloquent {
protected $table = 'tags';
protected $fillable = array('title', 'description');
protected $guarded = array('id');
}
迁移
Schema::create('taggable', function(Blueprint $table)
{
$table->increments('id');
$table->integer('taggable_id');
$table->string('taggable_type');
$table->integer('tag_id');
$table->timestamps();
});
DatabaseSeeder 片段
...
DB::table('taggable')->delete();
$track1 = Track::find(1);
$idm = Tag::find(1);
$track1->tags()->create(array('tag_id' => $idm->id));
...
任何有关此事的帮助将不胜感激。
最佳答案
尝试简化您的关系 - 您似乎正在使用中间表来允许标签重用 - 这是值得称赞的,但使您的问题变得复杂。
从标签和跟踪模型开始 - 在基本的多态关系发挥作用后添加额外的复杂性。
此外,问题可能是您的模型使用的名称与实际关系函数的名称相同。 IE Taggable->taggable() 与 Tag->taggable()
关于php - 多态关系和同名模型和 morphTo 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19125093/