Laravel 多态多对多不分离?
Laravel polymorphic many-to-many not detaching?
我有一个多态的多对多 User
/Location
- Group
关系,但我有时间让基本单元测试通过。
/** @test */
public function it_can_have_groups()
{
$user = factory(User::class)->create();
$group = factory(Group::class)->create();
$user->addToGroup($group);
$this->assertCount(1, $user->groups); // true
$user->removeFromGroup($group);
$this->assertCount(0, $user->groups); // false
}
这些方法只需根据 documentation:
调用 attach
和 detach
To remove a many-to-many relationship record, use the detach method. The detach method will delete the appropriate record out of the intermediate table; however, both models will remain in the database
public function addToGroup(Group $group)
{
$this->groups()->attach($group->id);
}
public function removeFromGroup(Group $group)
{
$this->groups()->detach($group->id));
dump($group->users()); // []
}
所以它似乎有效(?),但仅从组方面来看,断言仍然失败。为什么,我应该采取哪些不同的做法?
它可能就像您正在测试的模型具有陈旧的关系一样简单。试试这个:
/** @test */
public function it_can_have_groups()
{
$user = factory(User::class)->create();
$group = factory(Group::class)->create();
$user->addToGroup($group);
$this->assertCount(1, $user->groups->fresh()); // true
$user->removeFromGroup($group);
$this->assertCount(0, $user->groups->fresh()); // false
}
我有一个多态的多对多 User
/Location
- Group
关系,但我有时间让基本单元测试通过。
/** @test */
public function it_can_have_groups()
{
$user = factory(User::class)->create();
$group = factory(Group::class)->create();
$user->addToGroup($group);
$this->assertCount(1, $user->groups); // true
$user->removeFromGroup($group);
$this->assertCount(0, $user->groups); // false
}
这些方法只需根据 documentation:
调用attach
和 detach
To remove a many-to-many relationship record, use the detach method. The detach method will delete the appropriate record out of the intermediate table; however, both models will remain in the database
public function addToGroup(Group $group)
{
$this->groups()->attach($group->id);
}
public function removeFromGroup(Group $group)
{
$this->groups()->detach($group->id));
dump($group->users()); // []
}
所以它似乎有效(?),但仅从组方面来看,断言仍然失败。为什么,我应该采取哪些不同的做法?
它可能就像您正在测试的模型具有陈旧的关系一样简单。试试这个:
/** @test */
public function it_can_have_groups()
{
$user = factory(User::class)->create();
$group = factory(Group::class)->create();
$user->addToGroup($group);
$this->assertCount(1, $user->groups->fresh()); // true
$user->removeFromGroup($group);
$this->assertCount(0, $user->groups->fresh()); // false
}