【问题标题】:How to properly implement this polymorphic relationship in Laravel?如何在 Laravel 中正确实现这种多态关系?
【发布时间】:2019-11-11 03:08:00
【问题描述】:

我正在尝试在 Laravel 5.8 中为用户构建库存,但是这些项目有自己的属性,因此我需要设置多态关系。将项目附加到用户时,它会尝试将模型用户添加到 itemable_type 上的表中,并将用户 ID 添加到 itemable_id 以及将用户 ID 添加到 user_id,我可以通过传递我需要的模型来解决这个问题,但是当我尝试检索它们时,它会尝试查找 itemable_type = 'App\Models\User' 的项目,这让我觉得这里完全有问题。我可以对如何解决它有一些指导吗?

class User extends Model
{
    public function inventory()
    {
        return $this->morhpToMany(InventoryItem::class, 'itemable', 'user_inventories', null, 'itemable_id')
            ->withPivot('amount', 'notes');
    }
}
class InventoryItem extends Model
{
    public $timestamps = false;

    protected $table = 'character_inventories';

    protected $fillable = [
        'character_id', 'itemable_type', 'amount', 'parent_id', 'notes'
    ];

    public function cloth()
    {
        return $this->mophedByMany(Cloth::class, 'itemable');
    }

    public function food()
    {
        return $this->morphedByMany(Food::class, 'itemable');
    }

    // Other similar relations
}
// The Inventory migration:
 Schema::create('user_inventories', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->unsignedBigInteger('user_id');
    $table->unsignedInteger('itemable_id');
    $table->string('itemable_type');
    $table->unsignedInteger('amount')->default(0);
    $table->text('notes', 65535)->nullable();

    $table->foreign('character_id')->references('id')->on('characters');
});

预期的结果是用户模型在他的库存中有不同的项目,但关系试图通过加入自身并按用户类型而不是实际项目过滤来进行查询。

错误:

Syntax error or access violation: 1066 Not unique table/alias: 'user_inventories' (SQL: 
select `user_inventories`.*, 
    `user_inventories`.`itemable_id` as `pivot_itemable_id`, 
    `user_inventories`.`itemable_type` as `pivot_itemable_type`, 
    `user_inventories`.`amount` as `pivot_amount`, 
    `user_inventories`.`parent_id` as `pivot_parent_id`, 
    `user_inventories`.`notes` as `pivot_notes` 
from `user_inventories` 
inner join `user_inventories` on `user_inventories`.`id` = `user_inventories`.`itemable_id` 
where `user_inventories`.`itemable_id` in (4) 
and `user_inventories`.`itemable_type` = App\Models\User)

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    我高度怀疑您必须在 inventory 关系中引用用户表。一般来说,只要遵循Laravel 命名约定,就容易上百万倍。

    public function inventory()
    {
        return $this->morhpToMany(InventoryItem::class, 'itemable', 'users', null, 'itemable_id')
            ->withPivot('amount', 'notes');
    }
    

    【讨论】:

    • 感谢您的回答。据我所知,第三个参数是指关系发生的表(数据透视表)。尽管如此,我还是试了一下,确切地说,现在它尝试在users 表中查找所有字段(itemable_id、itemable_type 等)。问题是当我执行$user->inventory()->attach($inventoryItem) 时,它会将模型用户添加到itemable_type 字段中,当我尝试检索用户的库存时也是如此
    猜你喜欢
    • 2018-04-17
    • 1970-01-01
    • 2018-11-13
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多