希望有人能帮我解决这个问题,我有很久了,但现在才发上来。
我正在做的项目使用的是嵌套关系的模型。只是为了简化问题的背景,让我们想象一个父与多子的模型关系。hasMany
和 belongsTo
.
我通常会创建新的实例,并填写属性,然后我通过手工使用 setRelation()
和 associate()
方法(因为我喜欢用父子关系和子孙关系方法来检索关系)。toArray()
(在许多其他遍历其关系的模型方法中)。
问题是:我在做正确的事情,将其称为 setRelation
和 associate
为模型关系?如果没有,我如何检索 $model->children()
$model->parent()
关系?
我使用的是Laravel框架7.14.1和PHPUnit 8.5.5以及PHP 7.4.4(cli)。
这里有一个单元测试。
<?php
namespace Tests\Unit;
use PHPUnit\Framework\TestCase;
use Illuminate\Database\Eloquent\Model;
class Team extends Model {
protected $fillable = ['name'];
public function players()
{
return $this->hasMany(Player::class);
}
}
class Player extends Model {
protected $fillable = ['name'];
public function team()
{
return $this->belongsTo(Team::class);
}
}
class CircularReferencesTest extends TestCase
{
public function testCircularReference(): void
{
// new instances
$team = app(Team::class)->fill(['name' => 'team name']);
$player = app(Player::class)->fill(['name' => 'player name']);
// set relations
$team->setRelation('players', collect([$player]));
$player->team()->associate($team);
dd($team->toArray(), $player->toArray()); // ERROR: Segmentation fault (core dumped).
// dd($team->push()); // push calls save() method recursively @see https://laravel.com/docs/7.x/eloquent-relationships#the-push-method
dd($team, $player);
}
}
我在打电话./vendor/phpunit/phpunit/phpunit --stop-on-failure --colors=always ./tests/Unit/CircularReferencesTest.php
根据 这个
您不能在数据库中尚未表示的 2 个模型之间创建关系。
至少有一个模型必须预先保存,以便创建关系。
这是你代码中的第一个问题......
第二个问题:设置一方的关系是绰绰有余的......为什么你要从另一方设置关系?
我的意思是:
我的意思是: 这两行中的一行已经足够了
$team->setRelation('players', collect([$player]));
$player->team()->associate($team);
我更喜欢用'关联'的方法更清楚... ...