Laravel - Eloquent - 与名称空间的多态关系

Laravel - Eloquent - Polymorphic relationships with namespaces

我有 2 个 table 通过多态关系相关:

商店table:

id  |  name     |   ... 
15  |  my_store |   ...

以及通过 related_id 键和类型连接到商店 table 的标签 table。

id  |  related_id  |  tag   |  created  |  type  
1   |  15          |  test  |  00:00:00 |  store
2   |  15          |  dummy |  00:00:00 |  product

因此,在该示例中,商店 "my_store" 只有标签 "test"("dummy" 是产品的标签,而不是商店,此外它具有相同的 related_id).

我在我的代码中定义了 Store 模型,如下所示:

class Store extends Model {

protected $table = 'store';

public function tags()
{
    return $this->morphMany('App\Tag', 'related', 'type');
}
}

以及标签型号:

class Tag extends Model {

protected $table = 'tags';

public function related()
{
    return $this->morphTo();
}
}

但是当我尝试 运行

$store->tags;

我看到 Laravel 正在尝试 运行 的查询是:

SQL: select * from `mwp_tags` where `mwp_tags`.`related_id` = 46 
and `mwp_tags`.`related_id` is not null 
and `mwp_tags`.`type` = App\Store)

查询正在查找 App\Store 而不是 store

我无法更改数据库中的值,我不想使用

    protected $morphClass = 'store';

在 Store 模型中,因为我不知道是否必须创建另一个 morphMany 关系,可能使用另一个类型名称。

有人知道如何跳过这个问题吗?谢谢!

您可以尝试这样的操作:

public function tags()
{
    $default_morph_class = $this->morphClass ?: null;
    $this->morphClass = 'store';
    $morph_many_query = $this->morphMany('App\Tag', 'related', 'type');
    $this->morphClass = $default_morph_class;
    return $morph_many_query;
}

您的想法是即时更改 morphClass 并将其设置回去。这允许您为不同的关系使用不同的 morphClass。