【发布时间】: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)
【问题讨论】: